Search code examples
javaregexdigits

Java regular expression for digits and dashes


I need a regular expression which matches lines with only 4(four) hyphens and 13 digits(0-9). The order is undefined. I have regex like:

^([0-9\u2013-]{17})$

But, when I receive strings as

----123456789---- or 1-2-3-4-5-6-7-8-9 

matching is true but it must be false for me.

Could you please explain what I need use in order to matches were only with strings like 123-345-565-45-67 or 123-1-34-5435-45- or ----1234567890123 etc?


Solution

  • Try this regex:

    ^(?=(?:[^-]*-){4}[^-]*$)(?=(?:\D*\d){13}\D*$).*$
    

    Click for Demo

    Explanation:

    • ^ - asserts the start of the line
    • (?=(?:[^-]*-){4}[^-]*$) - positive lookahead to make sure that there are only 4 occurrences of - present in the string
    • (?=(?:\D*\d){13}\D*$) - positive lookahead to make sure that there are 13 occurrences of a digit present in the string
    • .* - once the above 2 lookaheads are satisified, match 0+ occurrences of any character except a newline character
    • $ - asserts the end of the line

    Escape \ with another \ in JAVA