skip to Main Content

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


  1. I think this is what you want:

    new RegExp('(^0(xd+)?$)|(^[1-9]d*$)')
    
    Login or Signup to reply.
  2. I got this Regular Expression to work with each of your examples:

    new RegExp('^(((?<![0-9])([1-9][0-9]*)?[0-9]?)x*)+$')
    

    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.

    Login or Signup to reply.
  3. An idea without use of lookarounds:

    ^b(?:(?:x|^)(?:0|[1-9]d*)?)+$
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search