Regular Expression ? -- Inserting Spaces

P

PJ

I'm having trouble with the Replace method on a RegEx instance. The target
value is "TermsOfUse" and I would like to get the string "Terms Of Use"
using regular Expressions. Here is what I have so far

String target = "TermsOfUse";
RegEx reg = New RegEx("(?<end>[a-z])(?<beg>[A-Z])");
Match check = reg.Match(target);
if ( check.Success )
target = reg.Replace(target, check.Groups["end"].Value + " " +
check.Groups["beg"].Value);

Console.WriteLine(target);
// spits out "Terms Os Ose"

It's replacing every Match, but only using the captures from the first
Match. How do I remedy this?

TIA~ PJ
 
B

Brian Davis

When you use Regex.Replace, you can use special sequences in the replacement
string to reference portions of the matched text. There really is no need
to make a call to Match and then to Replace; you can do it all with just the
Replace call. If there is no match, then the Replace will not do anything.
To reference named groups in a replacement string, use ${name}:

String target = "TermsOfUse";
RegEx reg = New RegEx("(?<end>[a-z])(?<beg>[A-Z])");
target = reg.Replace(target, "${end} ${beg}");


Brian Davis
www.knowdotnet.com
 

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