2

The target string is "A + A_RT + B*A+AA". I want to replace A with B and B with A. But I don't want to replace A_RT to B_RT or AA to BB. The expected result is "B + A_RT + A*B+AA". How can I do this in C#? Thanks.

Currently I use the following codes, but it will replace A_RT to B_RT...

IDictionary<string, string> map = new Dictionary<string, string>()
                                  {
                                      {"A","B"},
                                      {"B","A"},
                                  };

string str = "A + A_RT + B*A+AA";
var regex = new Regex(String.Join("|", map.Keys));
var newStr = regex.Replace(str, m => map[m.Value]);
2
  • You need to use look behind and look ahead to check whether there is any valid character for a name. Commented Oct 12, 2012 at 2:44
  • Append (?<!\w) before and (?!\w) after the regex to see whether it works or not. Commented Oct 12, 2012 at 2:48

3 Answers 3

2

I changed the regex to var regex = new Regex(@"\bA\b|\bB\b"), then it can work.

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

Comments

0

I'm not particularly good at regex patterns, so there is probably a better way to do this. But the pattern

@"([a-zA-Z_]+)"

was able to grab all your variable tokens as match results.

Comments

0

Use var regex = new Regex(String.Format("\\b[{0}]\\b",String.Join("", map.Keys)));

Comments

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.