简体   繁体   中英

pattern matching for String having “{”

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 error -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM