Hey StackExchange
Hey StackExchange

Reputation: 2125

Java: regexp excluding empty values

In the question here, I got the regexp to match one (or more) group of digits between 1 and 99 separated by | or , (both can be combined).

I want to update it to do the same, but accepting now digits between 0 and 99.

This modified version do that:

^(?:[0-9]|[1-9][0-9])?(?:[,|][1-9][0-9]?)*$ 1

But now accept empty values (see https://regex101.com/r/FfvavR/2)

Question

How can the regExp under 1 be modified to exclude empty value ?

Upvotes: 2

Views: 105

Answers (2)

alaster
alaster

Reputation: 4171

Just remove first occurrence of ?:. It makes group optional. So you have two optional groups that accepts empty string.

Also you can simplify [0-9]|[1-9][0-9] to [1-9]?[0-9] (? means first digit is optional)

Result:

^([1-9]?[0-9])(?:[,|][1-9]?[0-9])*$

Upvotes: 1

anubhava
anubhava

Reputation: 784998

It is unclear if 00 is a valid or invalid entry. If 00 is allowed then use this regex:

^[0-9]{1,2}(?:[,|][0-9]{1,2})*$ 

RegEx Demo 1

If 00 is not to be allowed then use this bit longish regex:

^([0-9]|[1-9][0-9])(?:[,|](?:[0-9]|[1-9][0-9]?))*$

RegEx Demo 2

Upvotes: 1

Related Questions