【问题标题】:replace specific letters in a string using regex使用正则表达式替换字符串中的特定字母
【发布时间】:2018-02-09 15:00:54
【问题描述】:

我需要用其他的替换一些特定的字母,例如:

“这是一个示范文本”

我需要更换

“tion”与“ting”

我试过这样的,

(1)正则表达式空格=新正则表达式(@"\b[a-zA-z]tion\b");
空格.替换(字符串,"ting");

(2)Regex.Replace(nonTagText, @"(\d+|.| )tion(\d+|.| )", "$1ting$2");

但它没有用。

谁能告诉我合适的正则表达式。提前致谢。

【问题讨论】:

  • 有什么原因不能使用 string.Replace() 吗?
  • 您的要求似乎比任何带有“ting”的字符串“tion”要多。什么情况下应该更换或不更换?您要替换的字符串示例和不应替换的其他示例通常很有帮助。
  • 您的字面问题的答案是Regex.Replace("This is an sample text for demonstration", "tion", "ting"),但我不知道这有多大帮助
  • 这里不需要Regex。 string str = "这是.......演示"; str = str.Replace("tion","ting");
  • 感谢您的回复。

标签: c# regex


【解决方案1】:

你的正则表达式可能是这样的:

 string mystring = "This is an sample text for demonstration";
            Regex space = new Regex(@"(?<=\w)+tion");
            string result = space.Replace(mystring, "ting");
            Console.WriteLine(result);

【讨论】:

    【解决方案2】:

    我找到了替代方法,谢谢你们的回复。

    String sourcestring = "This is alternate answer for demonstration";
    String matchpattern = @"tion";
    String replacementpattern = @"ting";              
    Console.WriteLine(Regex.Replace(sourcestring,matchpattern,replacementpattern));
    

    【讨论】:

    • 但这只是一个普通的字符串。替换
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2021-11-20
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    相关资源
    最近更新 更多