Regex with 2 matches in 1 substring

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
 
M

Michael Voss

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top