开发者

pattern matching for String having "{"

开发者 https://www.devze.com 2023-03-11 05:31 出处:网络
First I did this - String str = \"{\\\"hits\\\":[{\\\"links_count\\\":6,\\\"forum_count\\\":11}],\\\"totalHitCount\\\":1}\";

First I did this -

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");

This got me following error -

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

Then I did (escapes the "{") -

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");

and got the the following erro开发者_开发知识库r -

Exception in thread "main" java.lang.AssertionError: Partnership message does not appear expected:<true> but was:<false>

What am I missing here?


You don't need to escape { [ in your input. But you need to escape [ ] in your regex.

Try this:

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,}\\}"));


You're correct in escaping the curly braces within your regular expression (the string inside matches("...")), as otherwise they get interpreted as pattern repetition.

You should not, however, escape the curly braces inside str itself, as that'll only break things in your case.

There is this nice online tool which you may find useful in debugging Java regular expression.


The correct regexp is:

str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]+,\"forum_count\":[0-9]+\\}\\],\"totalHitCount\":[0-9]+\\}")


You were missing the Square brackets []

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

This will return true

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

精彩评论

暂无评论...
验证码 换一张
取 消