'How to exclude only negative numbers in parentheses from a string with Regex

I'm working in OCaml and I'm trying to find a regex that can match all the positive numbers in a string while excluding the negative ones between parentheses. My currently failing regex is:

^[1-9]+[0-9]*

and my sample is:

(-5) -> ignored : GOOD
5 -> matched : GOOD
(-19) -> ignored : GOOD
19 -> matched : GOOD
300free -> only 300 is matched : GOOD
5 + 8 -> only 5 is matched : BAD
(-1) + 5 -> 5 is not matched : BAD
5 + (-1) -> 5 is matched and (-1) is ignored: GOOD
1 (-1) -> 1 is matched and (-1) is ignored : GOOD
(-2) 1 -> 1 is not matched : BAD

My regex to match the negative ones, including the parentheses, is:

[(][-][0-9]+[)]

and it works properly. What should I change in the first regex to fix the BAD ones?



Solution 1:[1]

You could get the parts that you don't want out of the way, and use a capture group for the values that you want to keep.

\(\s*-\d+\s*\)|\b([1-9]\d*)
  • \(\s*-\d+\s*\) Match - and 1+ digits between parenthesis
  • | Or
  • \b A word boundary to prevent a partial match as the beginning
  • ([1-9]\d*) Capture group 1, match a digit 1-9 followed by optional digits 0-9

See a regex demo.


If you also want to allow matching 0, you can use

\(\s*-\d+\s*\)|\b(\d+)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 The fourth bird