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.
The expression \w will match any word character. Word characters include alphanumeric characters ( - , - and - ) and underscores (_). \W matches any non-word character.
Use the dot . character as a wildcard to match any single character.
?= 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).
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.
You'd better go with:
\d+(?![^{]*})
Explanations:
\d+ # Any digits
(?![^{]*}) # Negative lookahead - demonstrating to not within curly braces
Live demo
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])
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+(?=})
Debuggex Demo
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