NPS
NPS

Reputation: 6355

Regex for a semicolon-separated list

I have a list of words consisting of 1 or more a characters, separated by semicolons. The list can be empty. Is it possible to write a single regex expression that will match all possible valid lists and nothing else? Valid lists:

''
'a'
'aaaaa'
'a;a'
'aaa;a'
'a;aaaaa;aaa'

Invalid lists:

';aa'
'a;'
';'
'aaa;;a'

The closest thing I could come up with was either:

^(a+)*(;a+)*$

which matches an invalid ;a or:

^(a+)+(;a+)*$

which doesn't match the valid empty list.

Upvotes: 0

Views: 1427

Answers (1)

Tushar
Tushar

Reputation: 87233

^(a+(?:;a+)*)?$

  1. a+: Match a one or more times
  2. (?:;a+)*: Match one or more a zero or more times
  3. (...)?: To match ''(empty string)

Here's demo using HTML

input:valid {
  color: green;
  font-weight: bold
}
input:invalid {
  color: red;
}
<input type="text" pattern="(a+(?:;a+)*)?" placeholder="Type here" />

Same regex can also be written with OR(|) as

^(a+(?:;a+)*|)$

input:valid {
  color: green;
  font-weight: bold
}
input:invalid {
  color: red;
}
<input type="text" pattern="(a+(?:;a+)*|)" placeholder="Type here" />

Upvotes: 2

Related Questions