I am new to regex and am currently facing a problem in this regard.
I am trying to create a regular expression that matches a string in the following format:
OptionalStaticText{OptionalStaticText %(Placholder) OptionalStaticText {OptionalSubSection} OptionalStaticText} OptionalStaticText
Each Sectionor is Subsectionindicated by a symbol {...}. Each is Placeholderindicated by a symbol %(...). Each Sectionor Subsectionmay have an arbitrary permutation OptionalStaticText, %(Placholder)and OptionalSubSection.
To do this, I created a regular expression, which is given below (also can be seen here ).
/^(?:(?:(?:[\s\w])*(?:({(?:(?:[\s\w])*[%\(\w\)]+(?:[\s\w])*)+(?:{(?:(?:[\s\w])*[%\(\w\)]+(?:[\s\w])*)+})*})+)(?:[\s\w])*)+)$/g
This expression matches perfectly valid strings (for example: abc {st1 %(ph1) st11} int {st2 %(ph2) st22}{st3 %(ph3) st33 {st31 %(ph4) st332}} cdthat can be checked in the specified link).
However, it calls a timeout whenever the input string is invalid (for example:, abc {st1 %(ph1) st11} int {st2 %(ph2) st22}{st3 %(ph3) st33 {st31 %(ph4) st332}} c-dis -not a valid character according to a character group [\s\w]).
Such an invalid string causes a timeout using Catastrophic backtracking, which can also be tested in the link above.
I must have made a rookie mistake, but I don't know what. Is there any change I have to make to avoid this?
Thanks.
source
share