【问题标题】:I want to use the regex to split the string in java我想使用正则表达式在java中拆分字符串
【发布时间】:2017-05-28 10:22:58
【问题描述】:

这是我从文件中读取的内容:

(25 "如果" "\"急救.test()\"" ((286 13)) ()

我想把这个字符串拆分成

25 If "First aid.test()" 286 13

如何使用正则表达式拆分此字符串?

【问题讨论】:

  • 我没有看到任何分裂。您刚刚删除了一些字符。
  • 正则表达式用于用模式识别它。我认为你只需要用space替换一些字符
  • 我希望结果显示为一个数组,例如 [25, If, "First aid.test()", 286, 13]
  • @slivia 请记住在回答您的问题后接受最佳答案。

标签: java regex replace split str-replace


【解决方案1】:

编辑您的最新评论: 这不是很漂亮,但它会按照您在评论中的描述成功拆分您的字符串:

String input =  "(25 \"If\" \"\\\"First aid.test()\\\"\" ((286 13)) ()";
input = input.replaceAll("(?<!\\\\)\"|\\\\", "");
input = input.replaceAll("[)](?!\\\")|[(](?![)]\")", "");
input = input.replaceAll("(\".*?\")| ", "_$1");
String[] result = input.split("_+");
  • 第一次替换:删除所有前面没有\的“然后删除所有\
  • 第二次替换:删除所有相关(和)https://regex101.com/r/K2LS1c/1
  • 第三次替换:用 _match 替换引号或空格之间的所有匹配项
  • 在_上拆分

这将导致

[25, If, "First aid.test()", 286, 13]

它确实很丑,但它适用于你的字符串......

【讨论】:

  • 在很多情况下都会失败。例如,"If\\""test(wow(ok))"
  • 是的,这是一个非常糟糕的解决方案,但我们对输入知之甚少。你得到了我的投票
【解决方案2】:

拆分字符串不能产生不属于原始字符串的子字符串,例如...test()" 在原始字符串中显示为 ...test()\"。但是,您可以使用正则表达式来查找相关标记,然后根据需要对其进行处理。

public static void main(String args[]){
    String test = "(25 \"If\" \"\\\"First aid.test()\\\"\" ((286 13)) ()";
    Pattern extract = Pattern.compile("[^(\" )]+|(\"(\\\\\\\\|\\\\\"|[^\"])*\")");
    Matcher match = extract.matcher(test);
    List<String> tokens = new ArrayList<>();
    while(match.find()) {
        String token = match.group(0);
        if(match.group(1) != null) {
// FYI: consider using Apache StringEscapeUtils.unescapeJava(token);
            token = token.substring(1, token.length()-1);
            token = token.replace("\\\"", "\"");
        }
        tokens.add(token);
    }
    System.out.println(tokens);
}

输出:

[25, If, "First aid.test()", 286, 13]

【讨论】:

  • @slivia 我已根据您更新的要求更新了我的答案,以列表格式打印。
  • 非常感谢。这就是我想要的
  • @slivia Here 是当有人回答您的问题时该怎么做。要将答案标记为已接受,请单击答案旁边的复选标记以将其从灰色切换为已填充。无需对您的问题或答案添加评论以说“谢谢”。
猜你喜欢
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多