I'm trying to match digits but I need to follow some rules.
The digits may (or may not) start with a sign [+-].
If the digits start with a 0 it can NOT be followed by anything.
But if it's 0 by itself, it should be matched.
I came up with the following regular expression:
[+-]*[1-9]\d*|[+-]*[0](?!\w)
But it's not working exactly as I need:
01 (matches 1, should match nothing)
9,000 (matches 9 and last 0, should match 9 only)
+0152 (matches 152, should match nothing)
-1200 (matches -1200, working as intended)
+0 (matches +0, working as intended)
Live demostration
You can use this regex:
[+-]?\b(?:0|[1-9][0-9]*)\b
RegEx Demo
RegEx Breakup:
[+-]? - Match + or - optionally first\b - Assert a word boundary(?: - Start a non-capturing group
0 - Match a single 0| - OR[1-9][0-9]* - Match 1-9 followed by any digit 0 or more times) - End non-capturing group\b - Assert word boundaryTry the following Regex:
^[+-]?[1-9]\d*|[+-]*[0](?!\w)$
* after [+-] as it will match many signs, use ? instead.^ and $ so it matches the whole matching regex and giva wanted matches in your cases.Edit:
You will need to use word boundary \b instead of ^ and $, if you are dealing with words and not lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With