如何替换字符串并忽略下划线?字符串结构应保持原样。我不想删除下划线。只需将“世界”替换为“锐利”即可。并且只针对整个单词
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 ahead和look 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/