简体   繁体   English

正则表达式替换用短划线包围的一个字母

[英]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) 示例 :modif-i-ed => modifieded(-i-替换为y)

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

I tried 我试过了

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

But it generates for example modiyyed for the first example. 但它产生了例如第一个例子的modiyyed

The problem is that once the first - becomes optional, there are 2 matches inside modif-i-ed : f- and i- . 问题是,一旦第一-变得可选的,有2个匹配的内部modif-i-edf-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 -?[az]- to match and then replace: 我建议在-X-模式之前匹配和捕获字母,然后在匹配评估器中按原样返回它们,并使用-?[az]-匹配然后替换:

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

C#: 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 请参阅IDEONE演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM