Regex with 2 matches in 1 substring

  • Thread starter Thread starter Philipp Sumi
  • Start date Start date
P

Philipp Sumi

Hello Newsgroup

I'm using a simple Regex expression to extract placeholders enclosed in
"_" from a string as below:

string pattern = @"_(\S+)_";
string test1 = "the _first_ and the _second_ match";
string test2 = "param1=_first_&param2=_second_";


If I feed the first test string with the above pattern to the Regex
class, I'm getting 2 matches as expected:
_first_
_second_



However, this does not work anymore, if the placeholders are part of the
same substring like in the second example. test2 results in a single match:

_first_&param2=_second_


The Regex takes the longest substring, ignoring the delimiters in
between. I'm sure there is a very simple solution to get round that but
I don't get it...

Thanks for your advice

Philipp
 
Philipp said:
The Regex takes the longest substring, ignoring the delimiters in
between. I'm sure there is a very simple solution to get round that but
I don't get it...

Yes, there is: Make your Regex "lazy" by adding an "?":

@"_(\S+?)_" should work for your example.
 
Back
Top