Tarun
Tarun

Reputation: 3496

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?

Upvotes: 7

Views: 6820

Answers (4)

Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15453

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

Upvotes: 0

Diego Torres Milano
Diego Torres Milano

Reputation: 69318

The correct regexp is:

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

Upvotes: 3

Prince John Wesley
Prince John Wesley

Reputation: 63698

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

Upvotes: 5

NPE
NPE

Reputation: 500673

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.

Upvotes: 3

Related Questions