tags:

views:

114

answers:

5

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.

+1  A: 
(.)(?<!\1.)(?!\1)

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

ephemient
This answer address the question most directly, I wasn't sure if .NET regex support zero width assertions, but I looked it up and it does.
Tim
It should even work as `(?<!\1)(.)(?!\1)` - even though \1 is referenced before the capturing group. At least in .NET, Perl and Java, not in Python, JavaScript (and possibly others).
Tim Pietzcker
A: 

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

Regex.Replace(datePattern, "\\bd\\b", "dd")
Paul Mason
This was the problem. Thanks!
ATDev
A: 

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

Reg.Replace(datePattern, "/d/", "/dd/")
Tim
+1  A: 

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.

LukeH
The difference between yours and mine is that yours finds a single 'd' while mine finds a single any character. Dunno which suits OP's needs better.
ephemient
This works as a solution. Thanks!
ATDev
A: 

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);
John Fisher