RegEx Replace

  • Thread starter Brian Patterson
  • Start date
B

Brian Patterson

I'm using code similar to the following to search a line of code. I want to
replace what was found with a modified version of the text. My regex
pattern is "ListView\w*". And the line of text that I am matching against
is: "public static void AutoSizeListView(ref ListView lv)". My RegEx finds
two matches but I want the resulting string to look like:

public static void AutoSize%TG%ListView%TG%(ref %TG%ListView%TG% lv)

As you can see - I'm replacing the text that was found with the same text
but with a "%TG%" on the front and behind the text. I'm not quite sure how
to take my match value and use it again in the replace. Can someone help me
out?

Thanks!
Brian

---------------<snip>------------------
Regex r;
r = new Regex(@"ListView\w*",
RegexOptions.IgnoreCase|System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);
Match m = r.Match(@"public static void AutoSizeListView(ref ListView
lv)");
while (m.Success)
{
foreach (Group g in m.Groups)
{
foreach (Capture c in g.Captures)
{
Console.WriteLine("I found 1! " + c.Index.ToString() + " " +
c.Length.ToString() + " " + c.Value.ToString());
}
}
m = m.NextMatch();
}
 
?

=?iso-8859-1?B?u7cgRnJlZCC3qw==?=

Use the key characters '$&' to refer to the 'match found string'

string text = "public static void AutoSizeListView(ref ListView lv)";
string pattern = @"ListView\w*";
text = Regex.Replace(text, pattern, "%TG%$&%TG%");
 

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