Home > Software design >  Regex to replace a prefix string
Regex to replace a prefix string

Time:02-17

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.

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.

CodePudding user response:

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'
  • Related