【问题标题】:regular expression to get string in between special charecters正则表达式在特殊字符之间获取字符串
【发布时间】:2017-07-16 03:12:18
【问题描述】:

我正在尝试从字符串 ["october"] 中获取字符串 october 我尝试了替换方法

 tagNo = tagNo.replaceAll("\\[|\\]", ""); \\ it prints "october"

我不能用""替换引号。

 tagNo = tagNo.replaceAll("\\[|\\]", "").replaceAll("\"", "\\\\\"");

不替换引号打印\"october\"

但我更喜欢使用单个代码

使用regex 代码我如何在没有quotessquare bracket 的情况下获取字符串

【问题讨论】:

  • 你想解析 JSON 吗?然后不要使用正则表达式,而是使用 JSON 解析器。
  • 您应该听从@RolandIllig 的建议,但您可以使用tagNo.replaceAll("\\[\\W*(\\w+)\\W*\\]", "$1") 或者您可以将其用于特殊字符tagNo.replaceAll("\\[\"(.*)\"\\]", "$1")

标签: java regex


【解决方案1】:

您需要稍微更正您的正则表达式。您没有为删除双引号制定任何规则。试试这个,

tagNo = tagNo.replaceAll("(\\[|\"|\\])+", "");

【讨论】:

    【解决方案2】:
     tagNo = tagNo.replaceAll("[^a-zA-Z]+","");
    

    【讨论】:

    • 我想这就是答案
    【解决方案3】:
     tagNo = tagNo.replaceAll("\\[\"", "");
     tagNo = tagNo.replaceAll("\"\\]", "");
    

    参考Java replace all square brackets in a string

    Removing double quotes from a string in Java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多