替换字符串并忽略下划线

时间:2016-04-21 12:35:21

标签: c# regex string

如何替换字符串并忽略下划线?字符串结构应保持原样。我不想删除下划线。只是取代“世界”。用' sharp'。并且只针对整个单词

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);
}
输出应该是:

  

//你好

     

// helloworld

     

// hello_charp

     

// hello_charp _

4 个答案:

答案 0 :(得分:3)

像这样的东西 - 为了测试用于下划线,但包含它们用于匹配使用向前看看后面正则表达式结构。

  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')或undercope {{分隔的整个单词 1}}。

答案 1 :(得分:1)

您应该在_world

上使用替换
string[] sentences =
{
    "Hello",
    "helloworld",
    "hello_world",
    "hello_world_"
};
foreach (string s in sentences)
{

    string pattern = "_world";
    string result = s.Replace(pattern, "_charp");

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

为了防止Dmitry真的正确,还值得添加第二个替换

    string pattern1 = "_world";
    string pattern2 = " world";
    string result = s.Replace(pattern1, "_charp").Replace(pattern2, " charp");

答案 2 :(得分:0)

使用字符串替换功能参见此代码示例

using System;

class Program
{
    static void Main()
    {
    const string s = "Dot Net Perls is about Dot Net.";
    Console.WriteLine(s);

    // We must assign the result to a variable.
    // ... Every instance is replaced.
    string v = s.Replace("Net", "Basket");
    Console.WriteLine(v);
    }
}

输出

  Dot Net Perls是关于Dot Net的。    Dot Basket Perls是关于Dot Basket的。

答案 3 :(得分:0)

在评论中,您指定“世界应该用锐利替换”,那么为什么不能使用https://docs.python.org/3.4/library/string.html#formatspec进行简单替换

string wordToReplace="world";
string replaceWith="charp";
string[] sentences = { "Hello", "helloworld", "hello_world", "hello_world_" };
foreach (string  item in sentences)
{
    Console.WriteLine(item.Replace(wordToReplace,replaceWith));
}