Reputation: 3496
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
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
Reputation: 69318
The correct regexp is:
str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]+,\"forum_count\":[0-9]+\\}\\],\"totalHitCount\":[0-9]+\\}")
Upvotes: 3
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
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