正则表达式替换字符串

时间:2009-09-15 10:15:41

标签: c# regex

我尝试使用.NET正则表达式替换字符串中的 元素 - 没有运气:)

假设以下字符串:

 AA A  C D   A Some Text   here

规则

  1. 请勿在行尾添加
  2. 只替换单次出现
  3. 如果空格在其之前或之后(可选),请不要更换
  4. 上面所需的结果是(#替换字符):

     AA#A  C#D   A#Some Text   here

5 个答案:

答案 0 :(得分:2)

这应该涵盖您的所有3个要求。请原谅格式;我不得不回头勾选 的前几行才能正确显示。

string pattern = @"(?<!^|&nbsp;)((?<!\s)&nbsp;(?!\s))(?!\1)";

string[] inputs = { "&nbsp;AA&nbsp;A&nbsp;&nbsp;C&nbsp;D&nbsp;&nbsp; A&nbsp;Some Text &nbsp; here", // original

"&nbsp;AA&nbsp;A&nbsp;&nbsp;C&nbsp;D&nbsp;&nbsp; A &nbsp;Some Text &nbsp; here" // space before/after

};

foreach (string input in inputs)
{
    string result = Regex.Replace(input, pattern, "#");
    Console.WriteLine("Original: {0}\nResult: {1}", input, result);
}

<强>输出:

Original: &nbsp;AA&nbsp;A&nbsp;&nbsp;C&nbsp;D&nbsp;&nbsp; A&nbsp;Some Text &nbsp; here

Result: &nbsp;AA#A&nbsp;&nbsp;C#D&nbsp;&nbsp; A#Some Text &nbsp; here

Original: &nbsp;AA&nbsp;A&nbsp;&nbsp;C&nbsp;D&nbsp;&nbsp; A &nbsp;Some Text &nbsp; here

Result: &nbsp;AA#A&nbsp;&nbsp;C#D&nbsp;&nbsp; A &nbsp;Some Text &nbsp; here

答案 1 :(得分:1)

我不熟悉C#的特殊正则表达式风格,但在PERL / PHP风格中,这对我有用:

s/(?<!\A| |&nbsp;)&nbsp;(?!&nbsp;| )/#/g

这取决于负面的后观,负前瞻和\ A =输入转义序列的开始。

答案 2 :(得分:1)

您应该尝试以下示例:

string s = Regex.Replace(original, "(?<!(&nbsp;| |^))&nbsp;(?!(&nbsp;| ))", "#");

答案 3 :(得分:0)

答案 4 :(得分:0)

你可以使用这个

[^^\s(nbsp;)](nbsp;)[^$\s(nbsp;)]
相关问题