正则表达式替换符号并用引号引起来C#

时间:2019-06-30 16:33:39

标签: c# regex

我正在尝试在引号内替换'&'。

输入

"I & my friends are stuck here", & we can't resolve

输出

"I and my friends are stuck here", & we can't resolve

用'and'代替'&',仅在引号内,请您帮忙?

2 个答案:

答案 0 :(得分:1)

到目前为止,最快的方法是使用\G构造并使用单个正则表达式进行。

C#代码

var str =
    "\"I & my friends are stuck here & we can't get up\", & we can't resolve\n" +
    "=> \"I and my friends are stuck here and we can't get up\", & we can't resolve\n";
var rx = @"((?:""(?=[^""]*"")|(?<!""|^)\G)[^""&]*)(?:(&)|(""))";
var res = Regex.Replace(str, rx, m =>
        // Replace the ampersands  inside double quotes with 'and'
        m.Groups[1].Value + (m.Groups[2].Value.Length > 0 ? "and" : m.Groups[3].Value));
Console.WriteLine(res);

输出

"I and my friends are stuck here and we can't get up", & we can't resolve
=> "I and my friends are stuck here and we can't get up", & we can't resolve

正则表达式 ((?:"(?=[^"]*")|(?<!"|^)\G)[^"&]*)(?:(&)|("))

https://regex101.com/r/db8VkQ/1

解释

 (                          # (1 start), Preamble

      (?:                        # Block
           "                          # Begin of quote
           (?= [^"]* " )              # One-time check for close quote
        |                           # or,
           (?<! " | ^ )               # If not a quote behind or BOS
           \G                         # Start match where last left off
      )
      [^"&]*                     # Many non-quote, non-ampersand
 )                          # (1 end)

 (?:                        # Body
      ( & )                      # (2), Ampersand, replace with 'and'
   |                           # or,
      ( " )                      # (3), End of quote, just put back "
 )

基准

Regex1:   ((?:"(?=[^"]*")|(?<!"|^)\G)[^"&]*)(?:(&)|("))
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   10
Elapsed Time:    2.21 s,   2209.03 ms,   2209035 µs
Matches per sec:   226,343

答案 1 :(得分:0)

使用

Regex.Replace(s, "\"[^\"]*\"", m => Regex.Replace(m.Value, @"\B&\B", "and"))

请参见C# demo

using System;
using System.Linq;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var s = "\"I & my friends are stuck here\", & we can't resolve";
        Console.WriteLine(
            Regex.Replace(s, "\"[^\"]*\"", m => Regex.Replace(m.Value, @"\B&\B", "and"))
        );
    }
}

输出:"I and my friends are stuck here", & we can't resolve