2011-06-09 16 views
7

सबसे पहले मैं इस किया था -स्ट्रिंग होने के लिए मिलान पैटर्न "{"

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

यह मैं निम्नलिखित त्रुटि मिली

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 है जो आपको जावा नियमित अभिव्यक्ति डीबग करने में उपयोगी हो सकता है।

3

सही regexp है:

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

यह सच

Assert.assertTrue(str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]{1,},\"forum_count\":11\\}\\],\"totalHitCount\":[0-9]{1,}\\}"),"Partnership message does not appear"); 
वापस आ जाएगी
संबंधित मुद्दे