如何在 Java 字串中搜索一個模式?


Java 提供了 java.util.regex 包,用正則表示式進行模式匹配。你可以使用該包的類和方法在 Java 字串中搜索一個模式。

示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
   public static void main( String args[] ) {

      String line = "This order was placed for QT3000! OK?";
      String pattern = "(.*)(\d+)(.*)";
      Pattern r = Pattern.compile(pattern);
      Matcher m = r.matcher(line);
     
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0));
         System.out.println("Found value: " + m.group(1));
         System.out.println("Found value: " + m.group(2));
      }else{
         System.out.println("NO MATCH");
      }
   }
}

輸出

Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0

更新於: 20-Feb-2020

3 千瀏覽量 +

開啟你的 職業 生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.