2016-03-03 56 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();