2016-03-03 58 views
0

我正在嘗試學習Java正則表達式,並試圖將較小的字符串與另一個字符串進行匹配。以下是我提出的代碼。字符串不匹配,即使「patternString」是「text」的子字符串

String text = "this is the text to be searched for occurrences of the http://www.nba.com."; 
    String patternString = "http://.*"; 
    Pattern p1 = Pattern.compile(patternString); 
    Matcher m1 = p1.matcher(text); 
    boolean doesItMatch = m1.matches(); 
    System.out.println(doesItMatch); 
    System.out.println(m1.group()); 

我期待doesItMatch等於truem1.group()等於http://nba.com.。但是,IDE,而不是輸出

false 
Exception in thread "main" java.lang.IllegalStateException: No match found 
    at java.util.regex.Matcher.group(Matcher.java:536) 
    at java.util.regex.Matcher.group(Matcher.java:496) 
    at JTORegex.RegularExpression.main(RegularExpression.java:23) 
Java Result: 1 

爲什麼字符串patternString沒有對字符串匹配textpatternString確實存在於text之內。有人能告訴我爲什麼會發生這種情況嗎?預先感謝任何幫助!

回答

6

matches完整的字符串相匹配。使用find部分匹配

boolean hasAMatch = m1.find(); 
1

如何

boolean doesItMatch = m1.matches(); 
if (doesItMatch) 
    System.out.println(m1.group()); 
1

您可以使用

varname.find(); 

或布爾變量初始化它

boolean newvar = varname.find();