Reputation: 6355
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
Reputation: 87233
a+
: Match a
one or more times(?:;a+)*
: Match one or more a
zero or more times(...)?
: 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
input:valid {
color: green;
font-weight: bold
}
input:invalid {
color: red;
}
<input type="text" pattern="(a+(?:;a+)*|)" placeholder="Type here" />
Upvotes: 2