phpregexvalidationdigits

Validate a string containing a number, underscore, then an number with a maximum of 12 digits


I need to only allow the following format of a string to pass:

(any digit)_(any digit)

which would look like:

219211_2

So far I tried a lot of combinations, I think this one was the closest to the solution:

/(\\d+)(_)(\\d+)/

also if there was a way to limit the range of the last number (the one after the underline) to a certain amount of digits (ex. maximal 12 digits), that would be nice.


Solution

  • The following:

    \d+_\d{1,12}(?!\d)
    

    Will match "anywhere in the string". If you need to have it either "at the start", "at the end" or "this is the whole thing", then you will want to modify it with anchors

    ^\d+_\d{1,12}(?!d)      - must be at the start
    \d+_\d{1,12}$           - must be at the end
    ^\d+_\d{1,12}$          - must be the entire string
    

    demo: http://regex101.com/r/jG0eZ7

    Explanation:

    \d+      - at least one digit
    _        - literal underscore
    \d{1,12} - between 1 and 12 digits
    (?!\d)   - followed by "something that is not a digit" (negative lookahead)
    

    The last thing is important otherwise it will match the first 12 and ignore the 13th. If your number happens to be at the end of the string and you used the form I originally had [^\d] it would fail to match in that specific case.

    Thanks to @sln for pointing that out.