Using regex to match any character before reaching a substring?

I would like to be able to match a specific sequence of characters, starting with a specific substring and ending with a specific substring. My positive regex works if there is only one instance in the string, but not if there should be multiple matches in the string. I understand this because (. +) Grabs everything until the last positive expression is found. It would be nice if he captured everything until the first expression was found.

Here is my regex attempt:

@@FOO\[(.*)(?=~~)~~(.*)(?=\]@@)\]@@

Input Example:

@@FOO[abc~~hi]@@    @@FOO[def~~hey]@@

Desired conclusion: 2 matches, two suitable groups (abc, hi) and (def, hey) each.

Actual conclusion: 1 corresponds to two groups (abc ~~ hi] @@@@ FOO [def, hey)

Is there any way to get the desired result?

Thanks in advance!

+5
source share
3 answers

Use a question mark, it will match as few times as possible.

@@FOO\[(.*?)(?=~~)~~(.*?)(?=\]@@)\]@@

This also works, but not so strictly, although it is easier to read.

@@FOO\[(.*?)~~(.*?)\]@@
+5
source

The * operator is greedy by default, that is, it eats as many lines as possible, while preserving enough to match the remaining regular expression, can you do this not greedy by adding? to him. Be sure to read about the differences here.

+3
source

String.IndexOf(), .

0

All Articles