By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,214 Members | 1,496 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,214 IT Pros & Developers. It's quick & easy.

Regex replace help

P: n/a

I have a string like "bla<cut>blubb<cut>bla<cut>blubb" and want to replace
the substring from the first occurrence of <cut> to the second with "TEST"
in order to get "blaTESTbla<cut>blubb".
So far I only managed to get blaTESTblubb:

Regex iRegex = new Regex("<cut>.*<cut>");
return iRegex.Replace("bla<cut>blubb<cut>bla<cut>blubb", "TEST");
Mar 28 '06 #1
Share this Question
Share on Google+
4 Replies

P: n/a

Julius Fuchs wrote:

Regex iRegex = new Regex("<cut>.*<cut>");

You want non-greedy matching I think
Regex iRegex = new Regex("<cut>.*?<cut>");

Martin Honnen --- MVP XML
Mar 28 '06 #2

P: n/a
Martin Honnen wrote:
You want non-greedy matching I think
Regex iRegex = new Regex("<cut>.*?<cut>");

Thanks for your answer but that's not exactly what I wanted. Imagine the
following string: "a<cut>b<cut>c<cut>d<cut>e", with "<cut>.*?<cut>" as
pattern I would get "aTESTcTESTe" instead of "aTESTc<cut>d<cut>e" what I
Mar 28 '06 #3

P: n/a

The lazy (non-greedy) match indicated by Martin works but the lazy
matches are generally much slower than that standard (greedy) matches.

If performance is an issue you might look at

Regex iRegex = new Regex("<cut>\b\w*\b<cut>");

The \b (word boundary) prevents matching across multiple <cut> tags
NOTE: This will not find empty pairs (e.g. in bla<cut><cut>ddsd<cut>,
it will not find the <cut><cut>)


Regex iRegex = new Regex("<cut>((?!<cut>).)*<cut>")

where the negative lookahead prevents us passing the middle <cut>.
NOTE: This will find the empty pair


Mar 28 '06 #4

P: n/a


return iRegex.Replace("a<cut>b<cut>c<cut>d<cut>e", "TEST", 1);

This will return the string with only the first match replaced.



Mar 28 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.