简体   繁体   English

打字稿:正则表达式与预期模式不匹配

[英]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) 这个正则表达式的目的是匹配骰子命令,类似于roll20处理骰子命令的方式(例如1d10!投掷1d10,如果它应该落在10上,则投掷另一个d10,依此类推)

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})*? 最后一组([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. 作为附录,如果您对正则表达式本身有任何欢迎的输入,我敢肯定,有更有效的方式编写此正则表达式。

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})*? -> ([rf!<>=][1-9][0-9]{1,2})* . -> ([rf!<>=][1-9][0-9]{1,2})*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM