storyncode
storyncode

Reputation: 13

Typescript: Regex not matching expected pattern

I have the following regex in a typescript function:

/([1-9][0-9]*)*?[d]([468]|(?!(22|32|42|52|62|72|82|92|102|200|202))([12][20]{1,2}))([rf!<>=][1-9][0-9]{1,2})*?/g

The purpose of this regex is to match dice commands similar to how roll20 handles its dice commands (for example 1d10! rolls 1d10 and if it should land on a 10 it rolls another d10 and so on)

The first two groups work just fine (I can run this separately in my app and have confirmed they work as expected).

The final group ([rf!<>=][1-9][0-9]{1,2})*? does not match unless I add ^ to the start of the regex and $ to the end.

As an addendum, I'm sure there are more efficient ways of writing this regex - if you have any input on the regex itself that is welcome as well.

Upvotes: 1

Views: 828

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627517

A lazily quantified subpattern with *? at the end of the regex pattern will never match a single char, it will always match an empty string.

You need to replace the lazy quantifier with its greedy counterpart to avoid adding anchor here, ([rf!<>=][1-9][0-9]{1,2})*? -> ([rf!<>=][1-9][0-9]{1,2})*.

Upvotes: 2

Related Questions