0

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.

3
  • You may ommit the \b and \w as well as the braces around x:Uid. Try this instead: x:Uid=\"(\d)\" in order to retrieve the integers and then set replacement to {$1} Commented Oct 17, 2013 at 11:26
  • Just to make sure: Uids can only be exactly one digit long? Because \d matches exactly one digit. Commented Oct 17, 2013 at 11:29
  • So \d+ should be used if it's one or more digits? Commented Oct 17, 2013 at 11:38

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You´ll have to escape the " within your regex by using \"
@HimBromBeere - he already escaped it, by using "" (in a verbatim string, preceded by that @)
Shouldn't \d+ be used instead? Even thought the author did not state so I have a feeling it might be more than one digit in the real implementation :)
@flindeberg: Thus my comment/question above.
@TimPietzcker I totally missed that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.