1

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
chronos14
  • 99
  • 1
  • 12
  • 1
    You cannot use groups inside character classes. You can only list characters inside `[]`. – f1sh Sep 18 '19 at 11:40
  • 1
    Try `^(?!0+$)\d+$` https://regex101.com/r/wwqYkE/1 In java `String regex = "^(?!0+$)\\d+$";` – The fourth bird Sep 18 '19 at 11:41
  • Try `^(?!0).*` pattern – Dmitry Bychenko Sep 18 '19 at 11:41
  • 1
    the one that I checked is partially right. But the one that I'm looking for is this answer from @Thefourthbird . Thanks – chronos14 Sep 18 '19 at 12:08
  • 1
    @WiktorStribiżew i think the link that you claimed is different with my question. if I ask "how to match only the string that doesn't contain zero", then it will be a duplicate question. – chronos14 Sep 19 '19 at 01:50
  • @WiktorStribiżew no it is different. I gave the example though. if i follow that pattern, then 10000 will be invalid too because it contains zero. in my case 00100, 1000, 1000000000 is valid input. – chronos14 Sep 19 '19 at 07:37
  • So, this is a dupe of another question. Changed to [Need a regular expression - disallow all zeros](https://stackoverflow.com/questions/9609583/need-a-regular-expression-disallow-all-zeros). This topic is also covered very well on SO. Also, see [Regex: match everything but specific pattern](https://stackoverflow.com/questions/1687620/regex-match-everything-but-specific-pattern) to learn the ways to reject strings that match a generic pattern with exceptions. – Wiktor Stribiżew Sep 19 '19 at 07:40

2 Answers2

3

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.

Mena
  • 45,491
  • 11
  • 81
  • 98
2

If you want to check if string doesn't start from 0 (i.e. "01", "010" and "00100" are all invalid strings), you can try

^(?!0).*

pattern, where

^     - (anchor) start of the string
(?!0) - negative look behind (not start from 0)
.*    - any symbols 

or (without regular expressions)

bool result = !myString.startsWith("0");
Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186