使用正则表达式匹配多个匹配项或零个(按此顺序)
我想使用 Groovy 正则表达式匹配罗马数字(我没有在 Java 中尝试过,但应该是相同的)。 我在这个网站上找到了一个答案,其中有人建议使用以下正则表达式:
/M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})/
问题是像 /V?I{0,3}/
这样的表达式在 Groovy 中不是贪婪的。 因此,对于像“Book number VII”这样的字符串,匹配器 /V?I{0,3}/
返回“V”而不是所需的“VII”。
显然,如果我们使用模式 /VI+/
那么我们确实会得到匹配“VII”...但是如果字符串类似于“Book number V”,则此解决方案无效,因为我们不会得到任何结果匹配...
我尝试使用贪婪量词 /VI{0,3}+/
甚至 /VI*+/
强制捕获最大字符,但我仍然获得匹配“V”而不是“VII”
有什么想法吗?
I want to match roman numbers using Groovy regular expressions (I have not tried this in Java but should be the same).
I found an answer in this website in which someone suggested the following regex:
/M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})/
The problem is that a expression like /V?I{0,3}/
is not greedy in Groovy.
So for a string like "Book number VII" the matcher /V?I{0,3}/
returns "V" and not "VII" as it would be desired.
Obviously if we use the pattern /VI+/
then we DO get the match "VII"... but this solution is not valid if the string is something like "Book number V" as we will get no matches...
I tried to force the maximum character catching by using a greedy quantifier /VI{0,3}+/
or even /VI*+/
but I still get the match "V" over "VII"
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不只是 (IX|IV|V?I{1,3}|V) ?
Why not just (IX|IV|V?I{1,3}|V) ?
我发现我的错误是什么。
事实是,即使是空字符串也能满足像
/V?I{0,3}/
或/V?I*/
这样的模式......所以对于像这样的字符串“Book VII” 匹配器将抛出以下结果匹配:贪婪结果就在那里 (Result[5]) 好吧。
我的问题是我总是选择第一个匹配项(Result[0]),并且仅当空字符串不满足模式时才有效。
例如,建议的模式
/V?I{1,3}|V/
将仅抛出一个结果,因此选择第一个结果匹配即可:... 之所以如此,是因为该模式是不满足空字符串。
希望这对其他人有帮助
I found what my mistake was.
Thing is that patterns like
/V?I{0,3}/
or/V?I*/
are met even by EMPTY strings... so for a string like "Book VII" the matcher will throw the following result matches:The greedy result is there (Result[5]) alright.
My problem was that I was always picking the first match (Result[0]) and that is only valid if the pattern is not met by empty strings.
For instance, the suggested pattern
/V?I{1,3}|V/
will throw only one result, so picking the first result match is Ok:... This is so since the pattern is not met by empty strings.
Hope this helps others