Matthew Steven Monkan
Matthew Steven Monkan

Reputation: 9130

Help with simplifying a couple of regex's

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

Answers (4)

RandomEngy
RandomEngy

Reputation: 15413

.NET uses $ for backreferences:

text = Regex.Replace(text,
    @"\." + change.Key + "([,;])",
    "." + change.Value + "$1");

Upvotes: 2

fredw
fredw

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

Bruno Brant
Bruno Brant

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

Achim
Achim

Reputation: 15702

Out of my head:

text = Regex.Replace(text, @"\.(old|new),",@"\.\1;");

Upvotes: 0

Related Questions