Ahmad
Ahmad

Reputation: 9658

Regular Expression to replace one letter surrounded with dashes

I try to replace a specific letter surrounded by one or two dashes with another letter

Examples: modif-i-ed => modifyed (-i- is replaced with y)

a-im => eim (a- is replaced with e)

I tried

Regex.Replace(word, "-?([a-zA-Z])-", new_letter)

But it generates for example modiyyed for the first example.

Upvotes: 3

Views: 69

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

The problem is that once the first - becomes optional, there are 2 matches inside modif-i-ed: f- and i-. Thus, there are two replacements.

I suggest matching and capturing the letters before the -X- pattern and then return them as is in the Match evaluator, and use -?[a-z]- to match and then replace:

(\B[a-z](?=-))|-?[a-z]-

C#:

var myLetter = "y";
var str = " modif-i-ed  a-im  y-i-eld";
var res = Regex.Replace(str, @"(\B[a-z](?=-))|-?[a-z]-",
      m => m.Groups[1].Success ? m.Groups[1].Value : myLetter);
Console.WriteLine(res); // => modifyed  yim  yyeld

See IDEONE demo

Upvotes: 3

Related Questions