您必须越过单引号才能将它们从匹配中排除
更新
对于 C#,它必须像这样完成。
只需使用简单的 CaptureCollection 即可获取所有
引用的匹配项。
(?:'[^']*'|(?:"(([^"]*`")*[^"]*|[^"]*)")|[\S\s])+
展开
(?:
' [^']* '
|
(?:
"
( # (1 start)
( [^"]* `" )* # (2)
[^"]*
| [^"]*
) # (1 end)
"
)
|
[\S\s]
)+
C# 代码
var str =
"The two sentences are 'He said \"Hello there\"' and \"She said 'goodbye' and 'another sentence'\"\n" +
"\" `\" \"\n" +
"\" `\" \"\n" +
"\" `\" `\" \"\n" +
"\" `\" `\" `\" \"\n" +
"' \" \" '\n" +
"\"string\"\n" +
"\" 'xyz' \"\n" +
"\" `\" \"\n" +
"\" `\" `\" \"\n" +
"\" `\" `\" `\" \"\n" +
"' ' \"should match\" ' '\n" +
"' \"should not match\" '\n";
var rx = new Regex( "(?:'[^']*'|(?:\"(([^\"]*`\")*[^\"]*|[^\"]*)\")|[\\S\\s])+" );
Match M = rx.Match( str );
if (M.Success)
{
CaptureCollection cc = M.Groups[1].Captures;
for (int i = 0; i < cc.Count; i++)
Console.WriteLine("{0}", cc[i].Value);
}
输出
She said 'goodbye' and 'another sentence'
`"
`"
`" `"
`" `" `"
string
'xyz'
`"
`" `"
`" `" `"
should match
对不起,这是在PCRE引擎中完成的方式
'[^']*'(*SKIP)(*FAIL)|(?:"(([^"]*`")*[^"]*|[^"]*)")`
https://regex101.com/r/gMiVDU/1
' [^']* '
(*SKIP) (*FAIL)
|
(?:
"
( # (1 start)
( [^"]* `" )* # (2)
[^"]*
| [^"]*
) # (1 end)
"
)
___________________________-