Java 正则表达式中的 matches() 和 find() 有什么区别?

javaobject oriented programmingprogramming更新于 2024/5/8 16:44:17

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

Matcher 类的 ma​​tches() 和 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";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个 Matcher 对象
      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";
      //创建一个 Pattern 对象
      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

相关文章


有用资源