2011-06-09 148 views
7

首先,我這樣做 -模式具有字符串匹配 「{」

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> 

我在這裏錯過了什麼?

回答

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

你在你的正則表達式(內matches("...")字符串)內轉義大括號正確的,否則它們會解讀爲模式的重複。

你不應該,但是,逃跑的花括號內str本身,因爲這隻會破壞東西,你的情況。

有這個不錯的online tool,你可能會發現它在調試Java正則表達式中很有用。

3

正確的正則表達式是:

str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]+,\"forum_count\":[0-9]+\\}\\],\"totalHitCount\":[0-9]+\\}") 
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");