正则表达式捕获组未按预期工作 [英] Regex capturing group not working as intended

查看:111
本文介绍了正则表达式捕获组未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经挣扎了两天才能让它发挥作用,但我不能(我对正则表达式很糟糕:S)。

I've been struggling for two days to get this to work, but I just can't (I'm terrible at regular expressions :S).

${test}[arg]

从本文中,我需要检索两个不同的东西: test arg 。要做到这一点,我创建了这个正则表达式:

From this text, I need to retrieve two different things: test and arg. To do it, I have created this regex:

(\$\{(\b[a-zA-Z0-9.]+\b)\})(\[(.+)\])?

通过这个例子,它有效。但是,如果我尝试这个其他文本: $ {test} [arg1] - $ {test2} [arg2] ,我只得到一组有2组: test arg1] - $ {test2} [arg2 ,而不是获得2个不同的匹配:一个包含 test arg1 ,另一组包含 test2 arg2

With that example, it works. However, if I try this other text: ${test}[arg1] - ${test2}[arg2], I just get one match with 2 groups: test and arg1] - ${test2}[arg2, instead of getting 2 different matches: one with groups test and arg1, and the other with groups test2 and arg2.

我希望你能帮帮我。

谢谢你提前。

推荐答案

这是为什么。+ 的典型例子组合可能是邪恶的。改为使用否定字符集:

This is a classic example of why the .+ combination can be evil. Use a negated character set instead:

(\$\{(\b[a-zA-Z0-9]+\b)\})(\[([^]]+)\])
                              ^^^

您可以在此处试用。

比较两个表达式的行为:

Compare the behavior of the two expressions:


  • 贪婪地匹配任何内容。对于第二场比赛,正则表达式贪婪地匹配任何东西。它将匹配任何内容,直到它到达字符串的末尾,然后必须回溯直到它找到] 。一旦找到] ,它就会停止,因此你最终会得到 [arg1] - $ {test2} [arg2] 作为匹配。

  • Match anything greedily. For the second match, the regex matches anything greedily. It will match anything until it reaches the end of the string, and then has to backtrack until it finds a ]. As soon as it finds a ], it stops, hence you end up with [arg1] - ${test2}[arg2] as a match.

匹配除]以外的任何内容 。这里的正则表达式匹配任何不是] 的东西,因此每一步都检查下一个是] 或不。对于第二场比赛,你可以看到,一旦找到] ,它就会停止。

Match anything but a ]. Here the regex is matching anything that is not a ], therefore at every step is checks whether the next is a ] or not. For the second match, you can see that as soon as it finds a ], it stops.

这篇关于正则表达式捕获组未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆