Search code examples
regexbacktracking

Catastrophic backtracking searching for numbers in brackets


With this regex: \((\W*\d*\W*)*\) I am looking for numbers inside brackets. These numbers can be surrounded by any symbols but not characters and this pattern can appear a lot of times inside brackets, I mean I need to match everything here:

  • (8)
  • (8,)
  • ( 8'' )
  • (8, 9, 8 ,9)
  • (18, 9', 89;)
  • (' 7; 27; 37.38; 48 ; 55)

but NOT:

  • (8j)
  • (a888)
  • (1, 2; 12.13; 25.26; 35.36; 43.45; 52.56; 59,6o)

and exactly the last example gives me a Catastrophic backtracking error. How can I avoid this error? I really don't understand how to do it...


Solution

  • You could change your regex to \([\W\d]*\) which will match and not match your examples.

    See https://regex101.com/r/DNmuEb/1/