How to identify acronyms with Regex Javascript

Asked

Viewed 65 times

4

I need to identify acronyms that:

  • Start with P
  • Has 3 characters
  • The last 2 characters can be digits or letters.

Currently, I managed to create the regex \b(?:[A-Za-z0-9]){3} but unfortunately I’m not getting the rule of "start with P".

Some examples of acronyms would be: PCC, PC4, PCA, P00.

2 answers

2


The regex you are looking for is:

^P[a-zA-Z0-9]{2}$

Meaning:

^ - Inicio da linha
P - A letra P maiúscula
[a-zA-Z0-9]{2} - Uma letra ou um digito duas vezes
$ - Fim da linha

Example in JS:

const entrada = ['PCC', 'ABC', '9C4', 'PC4', 'XYZ', 'PCA', 'P00'];
for (let acronimo of entrada){
  console.log(acronimo, /^P[a-zA-Z0-9]{2}$/.test(acronimo));
}

In the example I used the method test of the regex directly within the console.log, but if you want to test alone on an if just do so:

if (/^P[a-zA-Z0-9]{2}$/.test(acronimoQueQuerTestar)){
    //acronimo valido
}

1

This regex solves your problem: /\bP[0-9A-Z]{2}\b/gi

Explaining:

  • \b is an important edge for results such as PCCC are not returned, see that there is one more letter.
  • [0-9] range from 0 to 9, ie numbers
  • [A-Z] interval from A to Z.
  • {2} quantifier that will catch only 2 letters.
  • g flag that captures all possible results.
  • i do not differentiate between capital letters and minuscules.

Running on regex101.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.