Java: regexp excluding empty values

前端 未结 2 450
孤街浪徒
孤街浪徒 2021-01-21 21:57

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

相关标签:
2条回答
  • 2021-01-21 22:48

    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])*$
    
    0 讨论(0)
  • 2021-01-21 22:57

    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

    0 讨论(0)
提交回复
热议问题