c# - 正则表达式应该只匹配两种类型的带引号的字符串之一
问题描述
我需要一个匹配用双引号括起来的字符串的正则表达式。如果此模式用单引号括起来,则它不应匹配用双引号括起来的字符串:
"string"
" 'xyz' "
" `" "
" `" `" "
" `" `" `" "
' ' "should match" ' '
' "should not match" '
现在我有(https://regex101.com/r/z5PayV/1)
(?:"(([^"]*`")*[^"]*|[^"]*)")
匹配所有行。但是最后一行不应该匹配。有什么解决办法吗?
解决方案
您必须越过单引号才能将它们从匹配中排除
更新
对于 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)
"
)
___________________________-
推荐阅读
- python - 如何在 jupyter 单元格中显示完整图形并导出完整图像而不是嵌入图像的一部分?
- python - pysftp/Paramiko 中的“类型对象‘EllipticCurvePublicKey’没有属性‘from_encoded_point’”
- azure - Azure 虚拟机预留
- sql - Sql Not IN 和 Not Exists 子句不适用于 Where 条件
- matlab - 从两个向量创建函数句柄以传递给 MATLAB 中的积分函数
- r - 如何标记一系列相同的值
- c# - Net Core 3.0 和桌面应用程序
- c# - 错误:远程服务器返回错误:(500)无效的 WSDL 访问,没有 SOAP 请求预期 C#
- sql - 在多对多(一张表)设计中苦苦挣扎
- python - 在数据框的每一列上使用具有不同功能的不同列上的 apply()