首先我这样做了 -
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");
这让我跟着错误 -
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
{"hits":[\{"links_count":[0-9]{1,},"forum_count":11}],"totalHitCount":[0-9]{1,}}
然后我做了(逃避“{”) -
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");
并收到以下错误 -
Exception in thread "main" java.lang.AssertionError: Partnership message does not appear expected:<true> but was:<false>
我在这里缺少什么?
答案 0 :(得分: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,}\\}"));
答案 1 :(得分:3)
你在正则表达式(matches("...")
中的字符串)中转义花括号是正确的,否则它们会被解释为模式重复。
然而,你不应该逃避str
内部的花括号,因为这只会破坏你的情况。
在调试Java正则表达式时,您可能会发现这个很好的online tool。
答案 2 :(得分:3)
正确的正则表达式是:
str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]+,\"forum_count\":[0-9]+\\}\\],\"totalHitCount\":[0-9]+\\}")
答案 3 :(得分:0)
你错过了方括号[]
String str = "{\"hits\":[{\"links_count\":6,\"forum_count\":11}],\"totalHitCount\":1}";
这将返回true
Assert.assertTrue(str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]{1,},\"forum_count\":11\\}\\],\"totalHitCount\":[0-9]{1,}\\}"),"Partnership message does not appear");