首页 > 解决方案 > 正则表达式应该只匹配两种类型的带引号的字符串之一

问题描述

我需要一个匹配用双引号括起来的字符串的正则表达式。如果此模式用单引号括起来,则它不应匹配用双引号括起来的字符串:

"string"
" 'xyz' "
"  `"    "
"  `" `"   "
"  `" `" `"  "
'  ' "should match" '  '
'   "should not match"   '

现在我有(https://regex101.com/r/z5PayV/1

(?:"(([^"]*`")*[^"]*|[^"]*)") 

匹配所有行。但是最后一行不应该匹配。有什么解决办法吗?

标签: c#regexdouble-quotessingle-quotes

解决方案


您必须越过单引号才能将它们从匹配中排除

更新

对于 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)
        "
   )

___________________________-


推荐阅读