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[(.*)(?=~~)~~(.*)(?=]@@)]@@
Sample input:
@@FOO[abc~~hi]@@ @@FOO[def~~hey]@@
Desired output: 2 matches, with 2 matching groups each (abc, hi) and (def, hey).
Actual output: 1 match with 2 groups (abc~~hi]@@ @@FOO[def, hey)
Is there a way to get the desired output?
Thanks in advance!
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[(.*?)~~(.*?)]@@
The * operator is greedy by default, meaning it eats up as much of the string as possible while still leaving enough to match the remaining regex. You can make it not greedy by appending a ? to it. Make sure to read about the differences at the link.
您可以使用String.IndexOf()方法来查找第一次出现的子字符串。
链接地址: http://www.djcxy.com/p/76730.html