Regex replace help

J

Julius Fuchs

Hi,

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");
 
J

Julius Fuchs

Martin said:
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
want.
 
A

AlanT

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>)

or

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

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

hth,
Alan
 
A

AlanT

Use

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.

aTESTc<cut>d<cut>e



hth,
Alan.
 

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

Similar Threads


Top