Catastrophic backtracking searching for numbers in brackets

Viewed 63

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...

2 Answers

The catastrophic backtracking for \((\W*\d*\W*)*\) is due to the nested optional quantifiers, and everything is optional.

Note that \W can also match ( and )

You can match any whitespace char except for chars A-Z a-z or parenthesis and assert at least a single digits between parenthesis if you need to match everything

\((?=[^()\d]*\d)[^A-Za-z()]+\)
  • \( Match (
  • (?=[^()\d]*\d) Assert at least a digit between the parenthesis
  • [^A-Za-z()]+ Match 1+ times any char except chars A-Z a-z ( ) and add more if you want to extend it
  • \) Match )

Regex demo

Related