C# 正则表达式替换引号C中的符号(&C)
我试图替换引号中的“&” 输入 输出C# 正则表达式替换引号C中的符号(&C),c#,regex,C#,Regex,我试图替换引号中的“&” 输入 输出 将“&”替换为“and”,并且仅在内部加引号,您能提供帮助吗?到目前为止,最快的方法是使用\G构造并使用单个正则表达式 C代码 正则表达式?:?=[^]*?使用 见: 输出:我和我的朋友们被困在这里,我们无法解决哇,我不知道有这么简单的方法让别人为你写正则表达式!美好的 "I & my friends are stuck here", & we can't resolve "I and my friends are stuck here",
将“&”替换为“and”,并且仅在内部加引号,您能提供帮助吗?到目前为止,最快的方法是使用\G构造并使用单个正则表达式 C代码 正则表达式?:?=[^]*?使用 见:
输出:我和我的朋友们被困在这里,我们无法解决哇,我不知道有这么简单的方法让别人为你写正则表达式!美好的
"I & my friends are stuck here", & we can't resolve
"I and my friends are stuck here", & we can't resolve
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
( # (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
Regex.Replace(s, "\"[^\"]*\"", m => Regex.Replace(m.Value, @"\B&\B", "and"))
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"))
);
}
}