如何替换字符串并忽略下划线?字符串结构应保持原样。我不想删除下划线。只需将“世界”替换为“清晰”即可。而且只针对整个单词
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_charp
// hello_charp_
这样的事情-为了测试潜望镜,但不将其包括在比赛中,请向前看并在正则表达式构造后面查看。
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));
在我的解决方案中,我假设您只想更改整个单词,这些单词由单词border('\b'
)或underscope分隔'_'
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句