Java正则表达式中matches()和find()的区别是什么?
java.util.regex.Matcher 类代表一个执行各种匹配操作的引擎。此类没有构造函数,您可以使用java.util.regex.Pattern类的matches()方法创建/获取此类的对象。
Matcher类的matches()和find()方法都尝试根据输入字符串中的正则表达式查找匹配项。如果匹配,两者都返回true;如果没有找到匹配项,则两者都返回false。
主要区别在于matches()方法尝试匹配给定输入的整个区域,即如果您尝试在某一行中搜索数字,则只有当该区域所有行中都包含数字时,此方法才返回true。
示例1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String regex = "(.*)(\d+)(.*)"; String input = "This is a sample Text, 1234, with numbers in between. " + "\n This is the second line in the text " + "\n This is third line in the text"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(input); if(matcher.matches()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } }
输出
Match not found
而find()方法尝试查找与模式匹配的下一个子字符串,即如果在该区域中至少找到一个匹配项,则此方法返回true。
如果您考虑以下示例,我们尝试匹配中间包含数字的特定行。
示例2
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String regex = "(.*)(\d+)(.*)"; String input = "This is a sample Text, 1234, with numbers in between. " + "\n This is the second line in the text " + "\n This is third line in the text"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(input); //System.out.println("Current range: "+input.substring(regStart, regEnd)); if(matcher.find()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } }
输出
Match found
广告