Java 中 Pattern MULTILINE 欄位及其示例


一般情況下啟用多行模式,無論其中包含多少行,元字元 ^ 和 $ 都匹配指定字元開頭和結尾。

示例 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
   public static void main( String args[] ) {
      //String regex = "(^This)";//.*t$)";
      String input = "2234 This is a sample text\n"
         + "1424 This second 2335 line\n"
         + "This id third 455 line\n"
         + "Welcome to Tutorialspoint\n";
      Pattern pattern = Pattern.compile("^([0-9]+).*");//, Pattern.MULTILINE);
      Matcher matcher = pattern.matcher(input);
      while(matcher.find()) {
         System.out.println(matcher.group(1));
      }
   }
}

輸出

2234 

當您將這用作 compile() 方法的標誌值時,整個輸入序列都將被視為單行,元字元 ^ 和 $ 匹配給定輸入序列的開頭和結尾。

示例 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
   public static void main( String args[] ) {
      //String regex = "(^This)";//.*t$)";
      String input = "2234 This is a sample text\n"
         + "1424 This second 2335 line\n"
         + "This id third 455 line\n"
         + "Welcome to Tutorialspoint\n";
      Pattern pattern = Pattern.compile("^([0-9]+).*", Pattern.MULTILINE);
      Matcher matcher = pattern.matcher(input);
      while(matcher.find()) {
         System.out.println(matcher.group(1));
      }
   }
}

輸出

2234
1424 

更新於: 05-Dec-2023

2K+ 瀏覽次數

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.