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

更新於:2019年11月20日

438 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.