1

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.

2
  • Remove the ?, use ([rf!<>=][1-9][0-9]{1,2})* Commented Feb 27, 2017 at 20:30
  • Ahh thank you, I thought that would be necessary to say it was optional, it seems I was mistaken. If you submit an answer and I will mark it as the accepted answer. Thanks! Commented Feb 27, 2017 at 20:53

1 Answer 1

2

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})*.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation of what I was doing wrong! It makes sense now that you've explained it.
Just FYI: ([rf!<>=][1-9][0-9]{1,2})*? grabs no chars because lazy subpatterns are skipped first, and all the subsequent ones are tried. Only if the subsequent subpatterns fail to match, the lazily quantified subpattern is "expanded", actually used by the regex engine, i.e. inverse backtracking occurs (kind of "forward-tracking").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.