【问题标题】:How can I escape these quotes in regex expressions?如何在正则表达式中转义这些引号?
【发布时间】:2014-07-12 11:27:08
【问题描述】:

我有一个字符串文本,类似于:

  "ruf": "the text I want",
     "puf":

我想提取引号内的文字。

试过这个:

         string cg="?<=\"ruf\":\")(.*?)(?=\",puf";
         Regex g = new Regex(cg);

它没有工作。

【问题讨论】:

  • 你想要ruf和puf吗?
  • 是多行字符串吗?
  • @AvinashRaj 没有。只是我想要的文字(不带引号)

标签: c# regex text


【解决方案1】:

试试下面的正则表达式:

(?<="ruf":\s\")[^"]*

Online demo

在程序中使用的字符串字面量:

C#

@"(?<=""ruf"":\s\"")[^""]*"

输出:

the text I want

图案说明:

  (?<=                     look behind to see if there is:
    "ruf":                   '"ruf":'
    \s                       whitespace (\n, \r, \t, \f, and " ")
    \"                       '"'
  )                        end of look-behind
  [^"]*                    any character except: '"' (0 or more times
                           (matching the most amount possible))

Debuggex Demo


编辑

你能加粉扑吗?因为它是一个长文本,其中包含多个引号

如果您正在寻找“puf”,请尝试以下正则表达式:

(?<="ruf":\s\")[\s\S]*(?=",\s*"puf")

Online demo

在程序中使用的字符串字面量:

C#

@"(?<=""ruf"":\s\"")[\s\S]*(?="",\s*""puf"")"

【讨论】:

  • 谢谢。可以加粉扑吗因为它是一个包含多个引号的长文本
  • 所以你一直在寻找直到找到“puf”。
【解决方案2】:

您可以尝试以下带有 s 修饰符的正则表达式,

/(?<=\"ruf\": \")[^\"]*(?=\",.*?\"puf\":)/s

DEMO

使用s 修饰符,点也匹配换行符。

【讨论】:

    【解决方案3】:

    这样做:

    var myRegex = new Regex(@"(?s)(?<=""ruf"": "")[^""]*(?=\s*""puf"")");
    string resultString = myRegex.Match(yourString).Value;
    Console.WriteLine(resultString);
    

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 1970-01-01
      • 2018-10-20
      • 2021-12-23
      • 1970-01-01
      • 2011-05-01
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多