使用正则表达式,直到达到一个子匹配任何字符? [英] Using regex to match any character until a substring is reached?
问题描述
我希望能够匹配字符的特定序列,从一个特定的字符串,并与特定的字符串结尾。我正向前查找正则表达式的作品,如果只有一个实例来匹配一条线,但如果应该有一行多个匹配。我明白这是因为(+)捕获了一切,直到的最后的阳性表达前瞻找到。它会是不错的,如果它能够捕捉一切,直到的第一个的表达被发现
I'd like to be able to match a specific sequence of characters, starting with a particular substring and ending with a particular substring. My positive lookahead regex works if there is only one instance to match on a line, but not if there should be multiple matches on a line. I understand this is because (.+) captures up everything until the last positive lookahead expression is found. It'd be nice if it would capture everything until the first expression is found.
下面是我的正则表达式的尝试:
Here is my regex attempt:
@@FOO\[(.*)(?=~~)~~(.*)(?=\]@@)\]@@
样品输入:
@@FOO[abc~~hi]@@ @@FOO[def~~hey]@@
所需的输出:2场比赛,2匹配组,每组(ABC,喜)和(闪避,嘿嘿)
Desired output: 2 matches, with 2 matching groups each (abc, hi) and (def, hey).
实际输出:1场2组(ABC ~~喜] @@ @@ FOO [闪避,嘿嘿)
Actual output: 1 match with 2 groups (abc~~hi]@@ @@FOO[def, hey)
有没有办法来获得所需的输出
Is there a way to get the desired output?
在此先感谢!
推荐答案
使用问号,它会比赛的几次越好。
Use the question mark, it will match as few times as possible.
@@FOO\[(.*?)(?=~~)~~(.*?)(?=\]@@)\]@@
这一次也适用,但没有那么严格,虽然更容易阅读
This one also works but is not as strict although easier to read
@@FOO\[(.*?)~~(.*?)\]@@
这篇关于使用正则表达式,直到达到一个子匹配任何字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!