我正在尝试学习Java正则表达式,并尝试将较小的字符串与另一个字符串进行匹配.以下是我提出的代码.
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());
Run Code Online (Sandbox Code Playgroud)
我期待着doesItMatch平等true和m1.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
Run Code Online (Sandbox Code Playgroud)
为什么字符串与字符串patternString不匹配text?patternString确实存在于text.为什么会这样?
matches匹配完整的String.使用find部分匹配
boolean hasAMatch = m1.find();
Run Code Online (Sandbox Code Playgroud)