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

标签 c# regex string

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

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/

相关文章:

Python字符串错误字符

c++ - 在 C/C++ 中进行不区分大小写的子字符串搜索的最快方法?

c# - 如何使用我的个人电脑在 windows iis 服务器上发布我的网站?

c# - 使用 ftpwebrequest 上传到 ftp 时图像损坏

javascript - 匹配类似 Excel 的引用单元格的正则表达式

php - 从地址字符串中提取邮政编码

c# - 上传文件导致错误 "net::ERR_UPLOAD_FILE_CHANGED"

c# - 如果你想确保所有的方法和属性都被实现,你用什么

regex - 当正则表达式为变量时,analyzer-string不匹配

java - 如何获取空格后面的单词首次出现后的剩余文本?