Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore digits that start with 0 (zero) using regular expression?

Tags:

regex

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

like image 426
Arthur Zopellaro Avatar asked Dec 07 '25 08:12

Arthur Zopellaro


2 Answers

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 boundary
like image 107
anubhava Avatar answered Dec 09 '25 15:12

anubhava


Try the following Regex:

^[+-]?[1-9]\d*|[+-]*[0](?!\w)$
  • You don't need * after [+-] as it will match many signs, use ? instead.
  • And you will need to wrap your regex between ^ 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.

like image 20
cнŝdk Avatar answered Dec 09 '25 16:12

cнŝdk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!