gpt4 book ai didi

c# - 替换字符串并忽略下划线

转载 作者:太空宇宙 更新时间:2023-11-03 21:12:28 29 4
gpt4 key购买 nike

如何替换字符串并忽略下划线?字符串结构应保持原样。我不想删除下划线。只需将“世界”替换为“锐利”即可。并且只针对整个单词

string[] sentences =
{
"Hello",
"helloworld",
"hello_world",
"hello_world_"
};
foreach (string s in sentences)
{

string pattern = String.Format(@"\b{0}\b", "world"); // whole case ignore underscore
string result = Regex.Replace(s, pattern, "charp");

Console.WriteLine(s + " = " + result);
}

输出应该是:

// Hello

// helloworld

// hello_charp

// hello_charp_

最佳答案

类似这样的事情 - 为了测试 underscopes,但不是include它们进入匹配使用look aheadlook behind 正则表达式结构。

  string[] sentences = new string[] {
"Hello",
"helloworld",
"hello_world",
"hello_world_",
"hello, my world!", // My special test
"my-world-to-be", // ... and another one
"worlds", // ... and final one
};

String toFind = "world";
String toReplace = "charp";

// do to forget to escape (for arbitrary toFind String)
string pattern = String.Format(@"(\b|(?<=_)){0}(\b|(?=_))",
Regex.Escape(toFind)); // whole word ignore underscore

// Test:

// Hello
// helloworld
// hello_charp
// hello_charp_
// hello, my charp!
// my-charp-to-be
// worlds

foreach (String line in sentences)
Console.WriteLine(Regex.Replace(line, pattern, toReplace));

在我的解决方案中,我假设您只想更改由单词边框('\b') 或下作用域 '_'

关于c# - 替换字符串并忽略下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36769830/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com