Best way to apply a pattern to the acronym

6

I have the following possible returns:

  • AB
  • A1
  • A

The first will always be a letter, the second may or may not occur and may be letter or number. In JavaScript it's like this (Example):

if (/^[A-Z][\w]$/.test(value.toUpperCase())) {
    callback(true)
} else if(/^[A-Z]$/.test(value.toUpperCase())) {
    callback(true)
} else {
    callback(false)
}

I would like to perform validation in only if .

    
asked by anonymous 18.09.2018 / 21:54

3 answers

4

The following regex solves your problem simply and without creating unnecessary groups.

/^[A-Z][A-Z0-9]?$/

Explanation:

  • ^ indicates that the occurrence must be at the beginning of the string, otherwise regex would match xxxA2 ;
  • [A-Z] : A character between A and Z
  • % with a% character between A and Z or between 0 and 9, this character being optional (occurs 0 or 1 time)
  • [A-Z0-9]? indicates that the occurrence must be at the end of the string, otherwise regex would match $ ;

Example:

var regex = /^[A-Z][A-Z0-9]?$/;

// Válidos
console.log("A:", regex.test("A"));
console.log("A1:", regex.test("A1"));
console.log("AB:", regex.test("AB"));

// Inválidos
console.log("1:", regex.test("1"));
console.log("A1 :", regex.test("A1 "));
console.log("A-:", regex.test("A-"));
    
18.09.2018 / 22:17
3

This Regex should meet:

/^[A-Z]([A-Z]*|\d+)$/

// validos
console.log(/^[A-Z]([A-Z]*|\d+)$/.test("A"))
console.log(/^[A-Z]([A-Z]*|\d+)$/.test("AB"))
console.log(/^[A-Z]([A-Z]*|\d+)$/.test("A1"))

//inválidos
console.log(/^[A-Z]([A-Z]*|\d+)$/.test("A-"))
console.log(/^[A-Z]([A-Z]*|\d+)$/.test("A@"))
console.log(/^[A-Z]([A-Z]*|\d+)$/.test("@1"))
console.log(/^[A-Z]([A-Z]*|\d+)$/.test("1A"))
    
18.09.2018 / 22:01
3

This regex can also serve you:

/^[a-z][a-z\d]?$/i

The i flag will dispense with the use of the .toUpperCase() method, because it will ignore if the letter is uppercase or lowercase.

Explanation:

[a-z]     O primeiro caractere é obrigatório ser uma letra
[a-z\d]  O segundo caractere é opcional, mas se existir
          deverá ser uma letra [a-z] ou um número \d

The ? makes [a-z\d] optional. The ^ and $ delimit the string to a maximum of 2 characters from the first.

Then if would be:

if(/^[a-z][a-z\d]?$/i.test(value)){
   callback(true);
}else{
   callback(false);
}

Test:

function valida(i){
   if(/^[a-z][a-z\d]?$/i.test(i)){
      callback(true, i);
   }else{
      callback(false, i);
   }
}

function callback(x, i){
   console.clear();
   console.log("'"+ i +"' é "+ x);
}
<p>Clique nos botões</p>
<button onclick="valida('a')">a</button>
<button onclick="valida('A')">A</button>
<button onclick="valida('aB')">aB</button>
<button onclick="valida('a#')">a#</button>
<button onclick="valida('a1')">a1</button>
<button onclick="valida('3A')">3A</button>
    
18.09.2018 / 22:51