2

A variable name can contain the characters [a-zA-Z0-9_] I want to replace all occurences of a particular variable name in an expression by some value. For example if the expression is a+aa-b and I want to replace the variable "a" by 1. The variable "aa" should not get replaced. The regex has to remember the unmatched portions, so that they can be copied over in the final expression. I need to get this done as part of a bigger project and don't have the time to read up in depth about regex. Please help.

3
  • What should happen to aø+aa? Note that ø is a letter according to Unicode, but it is not included in a-z. Commented Aug 11, 2012 at 17:59
  • For my requirement ø cannot appear in a variable name. Commented Aug 11, 2012 at 18:02
  • If you do not have enough time to learn regex, try implementing a simple token-based expression parser. It should be easy enough. Commented Aug 11, 2012 at 18:29

1 Answer 1

2

Use word boundaries surrounding the variable name:

Regex regex = new Regex(@"\ba\b");
string result = regex.Replace(input, replacement);

See it working online: ideone

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

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.