Maxrunner
Maxrunner

Reputation: 1965

How to validate a character where it must exist in specific conditions

So I have this regex expression:

(([aA-zZ]{2}[0-9]{5})(\w{2})?((XX)|(xx))?(\;)?)*

Basically it validates positive these examples:

zz01104;ZZ02045PA;
zz00110;AH12204
AG01104xx
EV99337xx;

It works as intended, the problem is this one:

zz00110AH12204;

There should be a ; between these two, but I don't know how can you control this directly with the regex expression.

Upvotes: 0

Views: 80

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627546

You should use

/^[a-zA-Z]{2}[0-9]{5}(?:\w{2})?(?:XX|xx)?(?:;[a-zA-Z]{2}[0-9]{5}(?:\w{2})?(?:XX|xx)?)*;?$/

See the regex demo.

In JS, you may build the pattern dynamically to avoid writing the regex parts twice:

var rxPart = "[a-zA-Z]{2}[0-9]{5}(?:\\w{2})?(?:XX|xx)?";
var rx = new RegExp("^" + rxPart + "(?:;" + rxPart + ")*;?$");
var strs = [ 'zz01104;ZZ02045PA', 'zz00110;AH12204', 'AG01104xx', 'EV99337xx', 'zz00110AH12204'];
for (var s of strs) {
  console.log(s, "=>", rx.test(s));
}

You can see that the pattern structure is

  • ^ - start of the string
  • rxPart - your single item pattern
  • (?: - start of a non-capturing group
    • ; - a semi-colon
    • rxPart - your single item pattern
  • )* - any 0 or more occurrences of the pattern sequence in the group
  • ;? - an optional ;
  • $ - end of string.

Upvotes: 1

Related Questions