Best way to apply a Pattern to the acronym

Asked

Viewed 62 times

6

I have the following possible returns:

  • AB
  • A1
  • To

The first will always be a letter, the second may or may not occur and may be letter or number. In Javascript it looks 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 the validation in just one if.

  • Ana, you said clearly that the first character is always a letter, ok. And in the second character, can come any character, example: !#$@%&*_-?

  • @sam the options for the second house will only be: see nothing, a letter or number.

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 the regex would match xxxA2;
  • [A-Z]: a character between A and Z
  • [A-Z0-9]? a character between A and Z or between 0 and 9, this character being optional (0 or 1 time occurs)
  • $ indicates that the occurrence must be at the end of the string, otherwise the regex would match A2xxx;

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-"));

  • I considered its correct alternative because it is simpler to understand visually than the other alternatives.

  • 1

    As I mentioned in the other answers, they’re good too, but they match some exceptions that you don’t want.

  • Yes. It also impacted my response.

3

This regex may also suit you:

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

The flag i will dispense with the use of the method .toUpperCase(), 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 ? causes the [a-z\d] is optional. The ^ and the $ define the string a maximum of 2 characters from the first.

Then the if would be:

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

Testing:

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>

3

This Regex must 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"))

  • The problem is that this regex will also marry values like A123456 or ABCDEFGHI. So the AP explained is only valid if it has 1 or 2 characters.

  • The problem is the *... it allows 0 or more repetition.. in which case it would only be 0 or 1 repetitions.. that’s what the ? makes. The + is also a problem because it allows 1 or more repetitions and falls into the same situation of *

  • can then limit the size: /^([A-Z]){0,1}([A-Z]|\d]*)$/

  • modifying your regex would be something like /^[A-Z]([A-Z]|\d]){0,1}$/. as the second character is optional.

  • Just remembering that {0,1} can be exchanged for ?: https://www.regular-expressions.info/optional.html

Browser other questions tagged

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