I need a RegExp to test strings that should consist of the valid whole decimal numbers including zero (0
, 1
, 12
, 123
, but not 00
or 0123
) mixed with a special character (such as x
) in free occurrences:
Examples of valid strings:
0
, 1
, 123
, x
, xx
, x0
, 0x
, x0x
, 0x0
, xx123x0
, x1000xx5xxx
, …
Invalid: 00
, x00
, 01
, x01
, … and basically all including wrong numbers (starting with 0
but not being a zero).
I came up with the following:
new RegExp('^0?$|^((?!0)[0-9]+|x0$|0x|x+)+$')
Unfortunately, it does not work 100%, e.g. a valid string is not accepted: 0x0
.
Thanks for any help!
3
Answers
I think this is what you want:
I got this Regular Expression to work with each of your examples:
I should note that it relies on a "negative lookbehind", which might not be supported by older environments. I have yet to run into any compatibility issues when using it in a modern browser.
RegExr.com can be quite helpful for visually explaining each part of a Regular Expression.
An idea without use of lookarounds:
See this demo at regex101
A word boundary
b
at^
start gets used to disallow empty matches (drop if such are wanted). The pattern is self-explanatory. Used are non-capture groups, alternation and basic quantifiers.