douwen0612 2013-07-11 08:13
浏览 52
已采纳

JSON的正则表达式

I have a string -

xyz":abc,"lmn

I want to extract abc. what will be the regular expression for this ?

I am trying this -

/xyz\":(.*?),\"lmn/

But it is not fetching any result.

  • 写回答

1条回答 默认 最新

  • dongshanya2008 2013-07-11 08:36
    关注

    In c# you could use

    var regex = new Regex(@"(?<=xyz\"":).*?(?=,\""lmn)");
    var value = regex.Match(@"xyz"":abc,""lmn").Value;
    

    Note this makes use of the c# verbatim string prefix @ that means that \ is not treated as an escape character. You will need to use a double " so that a single " will be included in the string.

    This regex makes use of prefix and suffix matching rules so that you can get the match without having to select the specific group from the result.

    Alternatively you can use group matching

    var regex=new Regex(@"xyz\"":(.*?),\""lmn");
    var value = regex.Match(@"xyz"":abc,""lmn").Groups[1].Value;
    

    You can check for the existence of a match by doing the following

    var match = regex.Match(@"xyz"":abc,""lmn");
    var isMatch = match.Success;
    

    and then follow up with either match.Value or match.Groups[1].Value depending on which regex you used.

    EDIT Actually the escaping the " is not needed in a c# regex so you could use either of the following instead.

    var regex = new Regex("(?<=xyz\":).*?(?=,\"lmn)");
    var regex = new Regex("xyz\":(.*?),\"lmn");
    

    These two do not use the verbatim string prefix, so the \" is translated into just " in the regex giving an a regex of (?<=xyz":).*?(?=,"lmn) or xyz":(.*?),"lmn

    Additionally if the is an entire string match rather than a substring you would want one of the following.

    var regex = new Regex("(?<=^xyz\":).*?(?=,\"lmn$)");
    var regex = new Regex("^xyz\":(.*?),\"lmn$");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测