Question

This is my first attempt to use regular expression.

What I want to archieve is to convert this string:

" <Control1 x:Uid="1"  />

  <Control2 x:Uid="2"  /> "

to

" <Control1 {1}  />

  <Control2 {2}  /> "

Basically, convert x:Uid="n" to {n}, where n represents an integer.

What I thought it would work (of course it doesn't) is like this:

  string input = " <Control1 x:Uid="1"  />
                   <Control2 x:Uid="2"  /> ";

  string pattern = "\b[x:Uid=\"[\d]\"]\w+";
  string replacement = "{}";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);

Or

  Regex.Replace(input, pattern, delegate(Match match)
  {
       // do something here
       return result
  });

I'm struggling to define the pattern and replacement string. I'm not sure if I'm in the right direction to solve the problem.

Was it helpful?

Solution

Square brackets define a character class, which you don't want here. Instead you want to use a capturing group:

string pattern = @"\bx:Uid=""(\d)""";
string replacement = "{$1}";

Note the use of a verbatim string to make sure the \b is interpreted as a word boundary anchor instead of a backspace character.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top