ATDev
ATDev

Reputation: 21

how do I replace nonrepeating character through .Net regular expression

I have a string. I want to replace "d" with "dd", using Regex.Replace, but only if the d is not repeating.

For example, if the string is "m/d/yy", i want to change it to "m/dd/yy". However, if the string is "m/dd/yy", i want to keep it the same, and NOT change it to "m/dddd/yy".

How do I do this? I tried Reg.Replace(datePattern, "\bd\b", "dd"), but that doesn't seem to work.

Upvotes: 0

Views: 251

Answers (5)

LukeH
LukeH

Reputation: 269628

You can use lookahead and lookbehind to check that each d isn't preceded or followed by another:

Regex.Replace(datePattern, "(?<!d)d(?!d)", "dd")

For the particular example in your question, plain string replacement would be more straightforward than using a regular expression: datePattern.Replace("/d/", "/dd/"). I'm guessing that your actual requirements are more complex, hence the regex.

Upvotes: 1

John Fisher
John Fisher

Reputation: 22717

A more simple approach is something like this:

Regex regex = new Regex(@"/(d|ddd)/");
string replacement = "/$1d/";
string updated = regex.Replace("m/d/yy", replacement);
string updated2 = regex.Replace("m/ddd/yy", replacement);
string notUpdated = regex.Replace("m/dd/yy", replacement);
string notUpdated2 = regex.Replace("m/dddd/yy", replacement);

Upvotes: 0

Tim
Tim

Reputation: 2419

I think this would work for what you are trying to do:

Reg.Replace(datePattern, "/d/", "/dd/")

Upvotes: 0

Paul Mason
Paul Mason

Reputation: 1129

I think that you are correct; although you may have escaped the characters incorrectly. Try:

Regex.Replace(datePattern, "\\bd\\b", "dd")

Upvotes: 0

ephemient
ephemient

Reputation: 204974

(.)(?<!\1.)(?!\1)

literally means "character, not preceded nor followed by itself".

Upvotes: 1

Related Questions