使用正则表达式匹配多个匹配项或零个(按此顺序)

发布于 2024-09-27 14:41:29 字数 527 浏览 11 评论 0原文

我想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一生独一 2024-10-04 14:41:29

为什么不只是 (IX|IV|V?I{1,3}|V) ?

Why not just (IX|IV|V?I{1,3}|V) ?

橪书 2024-10-04 14:41:29

我发现我的错误是什么。
事实是,即使是空字符串也能满足像 /V?I{0,3}//V?I*/ 这样的模式......所以对于像这样的字符串“Book VII” 匹配器将抛出以下结果匹配:

Result[0] --> ''
Result[1] --> '' 
Result[2] --> ''
Result[3] --> '' 
Result[4] --> '' 
Result[5] --> 'VII'
Result[6] --> '' 

贪婪结果就在那里 (Result[5]) 好吧。
我的问题是我总是选择第一个匹配项(Result[0]),并且仅当空字符串不满足模式时才有效。

例如,建议的模式 /V?I{1,3}|V/ 将仅抛出一个结果,因此选择第一个结果匹配即可:

Result[0] --> 'VII'

... 之所以如此,是因为该模式是不满足空字符串。

希望这对其他人有帮助

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:

Result[0] --> ''
Result[1] --> '' 
Result[2] --> ''
Result[3] --> '' 
Result[4] --> '' 
Result[5] --> 'VII'
Result[6] --> '' 

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:

Result[0] --> 'VII'

... This is so since the pattern is not met by empty strings.

Hope this helps others

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文