How to reject String "0" zero in Java with regex

chronos14 :

I have problem creating regex pattern to reject "0" value in String. I have tried to negate the string as follows

[^!(?0)]

but i believe this is wrong. Because it will also reject the String that contain zero, such as 10000". Is it possible to handle this with regex only? Because using if-else is easier though.

example:

  • "0" - invalid
  • "0000" - invalid
  • "10" - valid
  • "10000" - valid
Mena :

You can use:

^0+$

... and validate against it.

Essentially, it checks the input from start to end to make sure it's only made of 0s. You only need to invert the validation.

Or better:

!myString.matches("0+")

String#matches matches the whole string against a pattern. Negating the result of the invocation ensures only 0+ occurrences filling the whole string are invalid.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307327&siteId=1