English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Regex中的matchs()和find()有什么区别?

java.util.regex.Matcher中的类代表一个引擎,进行各种匹配操作。此类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取此类的对象。

两个匹配()发现()的Matcher类的尝试方法来根据 输入串中的正则表达式找到匹配。如果匹配,则两个都返回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";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个Matcher对象
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         System.out.println("找到匹配项");
      } else {
         System.out.println("找不到匹配项");
      }
   }
}

输出结果

找不到匹配项

而该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";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个Matcher对象
      Matcher matcher = pattern.matcher(input);
      //System.out.println("当前范围: "+input.substring(regStart, regEnd));
      if(matcher.find()) {
         System.out.println("找到匹配项");
      } else {
         System.out.println("找不到匹配项");
      }
   }
}

输出结果

找到匹配项