识别与某些目标文本匹配的替代项的正则表达式工具或方法?
在正则表达式的调试中,我需要找出替代方案中的哪个替代方案实际上导致了匹配。例如,对于目标字符串:
"foo"
使用正则表达式:
"f.*|other"
我需要一种方法来知道在上面的正则表达式中,备用 "f.*"
实际上导致了匹配。
在一些具有许多替代项的复杂正则表达式中,这对于调试来说非常具有挑战性。
In my debugging of regular expression, I need to find out which alternate among the alternatives actually resulted the match. For example, for the target string:
"foo"
with the regular expression:
"f.*|other"
I need a way to know that in the above regular expression, the alternate "f.*"
actually resulted the match.
In some complex regular expression with many alternates, this is very challenging for debug.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果每个备选方案都包含在其自己的捕获组中,则您知道只有其中一个组可以参加比赛。当您查询其他值时,它们将返回 null 或未定义的值。因此,您只需迭代捕获组,直到找到一个不为空的捕获组。详细的过程将取决于您使用的正则表达式风格和/或编程语言;有很大的变化。
因此,如果您的正则表达式是
(f.*)|(other)
并且它与foo
匹配,则组 #1 将包含foo
和组 # 2 将为 null(或nil
或undef
,具体取决于您使用的语言;但请注意,空字符串通常表示成功匹配,但未匹配消耗任何字符)。If each alternative is enclosed in its own capturing group, you know only one of those groups can participate in the match. The others will return a null or undefined value when you query them. So you just iterate through the capture groups until you find one that's not null. The detailed process will depend on which regex flavor and/or programming language you're using; there's a great deal of variation.
So, if your regex is
(f.*)|(other)
and it matchesfoo
, group #1 will containfoo
and group #2 will be null (ornil
, orundef
, depending on the language you're using; but be aware that an empty string usually indicates a successful match that didn't consume any characters).现在 MYRESULT 和 RESULT1 或 RESULT2 都将包含您的匹配项。
Now both MYRESULT and RESULT1 or RESULT2 will contain your match.