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.
1 Answer
Use word boundaries surrounding the variable name:
Regex regex = new Regex(@"\ba\b");
string result = regex.Replace(input, replacement);
See it working online: ideone
aø+aa? Note thatøis a letter according to Unicode, but it is not included in a-z.