Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to match numbers if a character is not a leading and trailing character

Tags:

regex

I need to match numbers as long as it is not found between { and }.

Examples:

{1}  - should not match  
1 - should match
2 - should match
{91} - should not match
3 - match
0 - match
{1212} - should not match

I wrote this (?!{)[\d](?!})

and it correctly matches those numbers outside { and } however when there is more than 1 digit in {} such as {123}, then it matches 12 excluding the last digit.

like image 339
user1875052 Avatar asked Apr 25 '14 07:04

user1875052


People also ask

Which pattern is used to match any non What character?

The expression \w will match any word character. Word characters include alphanumeric characters ( - , - and - ) and underscores (_). \W matches any non-word character.

How do you specify the regular expression to match a single character that is not an alpha or space character?

Use the dot . character as a wildcard to match any single character.

What does ?= Mean in regular expression?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

How do I match a number in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


2 Answers

You'd better go with:

\d+(?![^{]*})

Explanations:

\d+           # Any digits
(?![^{]*})    # Negative lookahead - demonstrating to not within curly braces 

Live demo

like image 87
revo Avatar answered Sep 26 '22 21:09

revo


If you want to also exclude numbers having curly bracket on only one side, like {123, 123}, then you can use the following regex (negative lookbehind and negative lookahead are used):

(?<![{\d])\d+(?![}\d])

Regular expression visualization

Debuggex Demo

If you want to include numbers having curly bracket on only one side, you can use or condition:

(?<![{\d])\d+(?![}\d])|(?<={)\d+(?![}\d])|(?<![{\d])\d+(?=})

Regular expression visualization

Debuggex Demo

like image 40
Ulugbek Umirov Avatar answered Sep 26 '22 21:09

Ulugbek Umirov