具有"{"的字符串的模式匹配

Tar*_*run 7 java regex

首先我这样做了 -

String str = "{\"hits\":[{\"links_count\":6,\"forum_count\":11}],\"totalHitCount\":1}";

        Assert.assertTrue(str.matches("{\"hits\":[{\"links_count\":[0-9]{1,},\"forum_count   \":11}],\"totalHitCount\":[0-9]{1,}}"),
            "Partnership message does not appear");
Run Code Online (Sandbox Code Playgroud)

这让我跟着错误 -

 Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
{"hits":[\{"links_count":[0-9]{1,},"forum_count":11}],"totalHitCount":[0-9]{1,}}
Run Code Online (Sandbox Code Playgroud)

然后我做了(逃脱"{") -

String str = "\\{\"hits\":[\\{\"links_count\":6,\"forum_count\":11\\}],\"totalHitCount\":1\\}";

    Assert.assertTrue(str.matches("\\{\"hits\":[\\{\"links_count\":[0-9]{1,},\"forum_count\":11\\}],\"totalHitCount\":[0-9]{1,}\\}"),
            "Partnership message does not appear");
Run Code Online (Sandbox Code Playgroud)

并得到以下错误 -

Exception in thread "main" java.lang.AssertionError: Partnership message does not appear expected:<true> but was:<false>
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

Pri*_*ley 5

您无需{ [在输入中转义.但是你需要[ ]在你的正则表达式中逃脱.

试试这个:

String str = "{\"hits\":[{\"links_count\":6,\"forum_count\":11}],\"totalHitCount\":1}";

System.out.println(str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]{1,},\"forum_count\":11\\}\\],\"totalHitCount\":[0-9]{1,}\\}"));
Run Code Online (Sandbox Code Playgroud)