Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to replace a prefix string

I want to replace a substring with a itself followed by a dot, when it is start of a longer sequence (i.e. it is a prefix). For example given the string:

"'abc' 'xyzabcdef' 'abcdef'"

I want to transform the prefix abc into abc., to give:

"'abc' 'xyzabcdef' 'abc.def'"

Note that the standalone string of abc is not transformed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried this code:

var input = @"'abc' 'xyzabcdef' 'abcdef'";
var result = Regex.Replace(input, @"\b(abc)\w+", @"$1.");
Console.WriteLine(result);

which gives:

'abc' 'xyzabcdef' 'abc.'

Note in the third output, the trailing def is also substituted. I expected the substitution of $1 would have been associated with just the group (abc), but it clearly matches the entire pattern. I’m looking for the correct formulation of the Regex.Replace() call.

>Solution :

Try replacing on the regex pattern (?<=')abc(?=\w). This pattern says to match:

(?<=')  assert that single quote precedes
abc     match and consume abc
(?=\w)  assert that at least one word character follows
var input = @"'abc' 'xyzabcdef' 'abcdef'";
var result = Regex.Replace(input, @"(?<=')abc(?=\w)", @"abc.");
Console.WriteLine(result);  // 'abc' 'xyzabcdef' 'abc.def'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading