Search code examples
javaregexgreedycharacter-class

Match input starting with non-number or empty string followed by specific pattern


I'm using Java regular expressions to match and capture a string such as:

0::10000

A solution would be:

(0::\d{1,8})

However, the match would succeed for the input

10::10000

As well, which is wrong. Therefore, I now have:

\[^\d\](0::\d{1,8})

Which means it must lead with any character except a number, but that means there needs to be some character before the first zero. What I really want (and what I need help with) is to say "lead with a non-number or nothing at all."

In conclusion the final solution regular expression should match the following:

0::10000
kjkj0::10000

And should not match the following:

10::10000

This site may be of use if someone wants to help.


Solution

  • You need a negative lookbehind:

    (?<!\d)(0::\d{1,8})
    

    It means "match 0::\d{1,8} not preceded by \d".