I have strings like this:
- 123456-0001
- 123456-0012
- 123456-0123
How to match with next conditions:
- chars count after – should be 4
- zeros count variable – from 1 to 3
I found ^\d{6}-0+([1-9]+)$ pattern but it matches for 123456-001 or 123456-00001.
>Solution :
You can use
^\d{6}-(?=\d{4}$)0+([1-9]\d*)$
See the regex demo.
Details:
^– start of string\d{6}– six digits-– a hyphen(?=\d{4}$)– from this position and to the end of string, there must be four digits0+– one or more zeros([1-9]\d*)– Group 1: a non-zero digit and then any zero or more digits$– end of string (use\zif you need the very end of string).
Note:
(?=\d{4}$)is the positive lookahead that enforces the four digit only rule0+– makes a zero required (so one or more zeros is enforced)([1-9]\d*)captures any non-zero digit and then any digits including zeros (0100will now get matched, too.)
Also, consider checking \d vs. [0-9] at \d less efficient than [0-9].