【问题标题】:Find and replace a part of a sring查找和替换字符串的一部分
【发布时间】:2021-11-15 07:30:36
【问题描述】:

我想在c#中使用正则表达式突出显示两端带有“*”的字符串部分

我尝试过的:

replaced = Regex.Replace(text, @"\b123\b", "*123*");
replaced = Regex.Replace(text, @"\b234\b", "*234*");
replaced = Regex.Replace(text, @"\b335\b", "*335*");

例子:

突出显示:123、234、335

输入:dsadf335aa
输出:dsadf*335*aa

我的问题是我有一个要查找的字符串列表,但我不知道如何搜索所有这些。

编辑:

我尝试过 D Stanley 的建议,但有问题。 第二个{s}被理解为字符串...

sintax

【问题讨论】:

  • 你的意思是每个字符串s 用*s* 替换\bs\b? foreach(string s in list) { text = Regex.Replace(text, $@"\b{s}\b", "*{s}*");} 怎么样?
  • 另外,我认为您在这里不需要正则表达式 - text.Replace() 应该足够好了。
  • text = Regex.Replace(text, @"\d+", "*$0*");

标签: c# regex


【解决方案1】:
foreach (string s in list) 
{ 
    replaced = string.Format("*{0}*", s);
    newtexe = Regex.Replace(text, s, replaced);

    if (text != newtexe) 
       { break; } 
}

解决了 :D 感谢帮助 :))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2020-05-27
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    相关资源
    最近更新 更多