Regular Expression -seems to be easy but nobody knows

WeeDie
WeeDie used Ask the Experts™
on
k, I'm runnig a loop over a Regex.Replace method i C# and I want the pattern to match only ONCE!


strLayout = "<p>;;firstname;;</p><p>;;lastname;;</p>";
for (int i=0;i<2;i++)
{
strLayout = Regex.Replace(strLayout,";;[^;]*;;",dbRow[i].ToString());
}

the resulting strLayout will look something like this in the after the first loop "<p>Firstname</p><p>Firstname</p>";

and then no matches will be found in the second loop which would print this if things get the way I want them.
<p>Firstname</p><p>Lastname</p>

seems to me it would be setting the whole pattern to non-greedy but I don't know how to do that, and noone else that I've asked either, and I haven't found any example in any regular expression documentation. If you know this please break this one for me.

//WeeDie
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
When I think of the term "Greedy" in a regular expression, I think of PERL regular expressions.

Consider the string "addd".

In perl, matching is greedy by default, so

/.*d/ will match "addd"

If I tell it to be non-greedy then

/.*?d/ will match "ad"

What you really want is that the Replace method in C# only match the first occurrence. From what I can find, it behaves as:

"The Regex class also contains a Replace method, which substitutes text whenever a pattern is matched."

So it always matches as many times as it can.

We know, however, that...

"the System.Text.RegularExpressions classes, and is based on the Perl 5 syntax for Regular Expressions. "

If you check out

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemtextregularexpressionsregexoptionsclasstopic.asp

It says very specifically that:

Replaces all occurrences of a character pattern defined by the regular expression specified

There claims to be a method that will do as you desire... check out:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemtextregularexpressionsregexclassreplacetopic4.asp

I guess that you will have to construct your regular expression (rather than using a static method) and then use the version that allows you to specify the maximum number of replacements to make.

Andrew

Author

Commented:
doh! yeah that would work just as good, sorry for troubleing you, I just find it very hard to getting right in MSDN, and when you're on a 28 modem it really gets frustrating >_< Thanks a lot for your help though, you saved my day =)
Commented:
Glad I could help.. Please clouse out the question then.

Andy

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial