Regular Expression ? -- Inserting Spaces

  • Thread starter Thread starter PJ
  • Start date Start date
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
 
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
 
Back
Top