正則表示式“\Z”元字元在 Java 中


子表示式/元字元“\Z”匹配整個字串的結尾,但不允許行尾終結符。

示例 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "Tutorialspoint\z";
      String input = "Hi how are you welcome to Tutorialspoint";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

輸出

Number of matches: 1

示例 2

下面的 Java 程式驗證了指定的輸入文字是否以數字結尾。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Data {
   public static void main( String args[] ) {
      String regex = "[0-9]\z";
      String input = "Hi how are you \n this is sample text \n this is third line 554";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      if(m.find()) {
         System.out.println("Given input ends with a digit");
      } else {
         System.out.println("Given input doesn’t end with a digit");
      }
   }
}

輸出

Given input ends with a digit

更新日期:2019 年 11 月 19 日

441 次瀏覽

開啟你的職業生涯

透過完成課程取得認證

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