-1

I have this regex, which works as on this link: https://regex101.com/r/HVKfYU/1

This is my regex string: (\d+[-–]\(?\d+([+\-*/^]\d+ ?[+\-*/^] ?\d+)?\)?)

These are my test strings:

(0–(2^63 - 1))
(1-(2^16 - 2))
(1-29999984)
(3-32)

This is what the regex matches in the first two cases:

0–(2^63 - 1)
1-(2^16 - 2)
// works, it doesn't match the first pair of brackets

And this is what it matches in the last two:

1-29999984)
3-32)
// doesn't work, it matches the closing bracket

I'd like it to not match the last closing bracket in any of the test strings. At the moment I'm stripping the bracket if necessary, but I would like to avoid that. How could I modify the regex, so it works as I would like?

Teodor Maxim
  • 85
  • 2
  • 6
  • 1
    Do you always have only up to two levels of paranthesis? If not, you likely don't want to use regex for this problem, since it's inherently recursive. See the answer here: https://stackoverflow.com/questions/546433/regular-expression-to-match-balanced-parentheses – panmari Jun 10 '20 at 20:53
  • @panmari At the moment it does, and I don't expect the input to get more complicated in the future. I will check your answer though. – Teodor Maxim Jun 10 '20 at 21:00

1 Answers1

1

Try (\d+[-–](?:\d+|\(\d+([+\-*/^]\d+[ ]?[+\-*/^][ ]?\d+)?\)))

demo

it just match digits or block with paren


add some explern

 (       
   \d+ [-–] 

   (?:     # non capture for alternation

     \d+          # dd-dd form

     |         # or

     \( \d+       # dd-(dd + dd) form
     (                       
          [+\-*/^] 
          \d+ 
          [ ]? 
          [+\-*/^] 
          [ ]? 
          \d+ 
     )?
     \) 
   )
 )
  • Thank you, it works as intended. Could you explain what effect does the non-capturing group in the regex has? – Teodor Maxim Jun 11 '20 at 07:28
  • afddes sum explern. non-captur just houses alternation. yure same regex just instead of optional paren, made alternate require paren or no paren at all –  Jun 11 '20 at 17:40