Reputation: 9130
Below I have two regex's that operate on some text:
assume key = "old" and value = "new"
text = Regex.Replace(text,
"\\." + change.Key + ",",
"." + change.Value + ","
);
text = Regex.Replace(text,
"\\." + change.Key + ";",
"." + change.Value + ";"
);
So, ".old," and ".old;" would change to ".new," and ".new;", respectively.
I'm sure this could be shortened to one regex. How can I do this so that the string only changes when the comma and semicolon are at the end of the variable? For example, I don't want ".oldQ" to change to ".newQ". Thanks!
Upvotes: 0
Views: 68
Reputation: 15413
.NET uses $ for backreferences:
text = Regex.Replace(text,
@"\." + change.Key + "([,;])",
"." + change.Value + "$1");
Upvotes: 2
Reputation: 1419
I like using \b, like this:
text = Regex.Replace(text, @"\." + change.Key + @"\b", "." + change.Value);
It would match on keywords followed by other delimiters, not just "," and ";", but it may still work in your case.
Upvotes: 0
Reputation: 8564
You want to just change the middle part, so:
text = Regex.Replace(text,
"\\." + change.Key + "(,|;)^", // mark a group using "()" for substitution...
"." + change.Value + "\1" // use the group ("\1")
);
Upvotes: 0
Reputation: 15702
Out of my head:
text = Regex.Replace(text, @"\.(old|new),",@"\.\1;");
Upvotes: 0