用於表示一個大於 10 的十六進位制數字且長度必須為偶數的 Java 正則表示式。


以下是匹配大於 10 且長度為偶數的十六進位制數字的正則表示式 -

^(?=.{10,255}$)(?:0x)?\p{XDigit}{2}(?:\p{XDigit}{2})*$

其中,

  • ^ - 匹配句子的開頭。

  • (?=.{10,255}$) - 以 10 到 255 個字元結尾的字串。

  • \p{XDigit}{2} - 兩個十六進位制字元。

  • (?:\p{XDigit}{2})* - 0 個或多個雙十六進位制字元序列。

  • $ - 匹配句子的結尾。

範例 1

 動態演示

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaExample51 {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      String nums[] = new String[5];
      for(int i=0; i<nums.length; i++){
         System.out.println("Enter a hexa-decimal number: ");
         nums[i] = sc.nextLine();
      }
      //Regular expression to accept English alphabet
      String regex = "^(?=.{10,255}$)(?:0x)?\p{XDigit}{2}(?:\p{XDigit}{2})*$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      for (String hex : nums) {
         //Creating a Matcher object
         Matcher matcher = pattern.matcher(hex);
         if(matcher.find()) {
            System.out.println(hex+" is valid");
         }else {
            System.out.println(hex+" is not valid");
         }
      }
   }
}

輸出

Enter a hexa-decimal number:
0x1234567890
Enter a hexa-decimal number:
123456789
Enter a hexa-decimal number:
123456789012
Enter a hexa-decimal number:
sfdgdf35364
Enter a hexa-decimal number:
$@%#BV#*
0x1234567890 is valid
123456789 is not valid
123456789012 is valid
sfdgdf35364 is not valid
$@%#BV#* is not valid

範例 2

 動態演示

import java.util.Scanner;
public class JavaExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a hexa-decimal number: ");
      String name = sc.nextLine();
      String regex = "^(?=.{10,255}$)(?:0x)?\p{XDigit}{2}(?:\p{XDigit}{2})*$";
      boolean result = name.matches(regex);
      if(result) {
         System.out.println("Given number is valid");
      }else {
         System.out.println("Given number is not valid");
      }
   }
}

輸出 1

Enter your name:
0x1234567890
Given name is valid

輸出 2

Enter a hexa-decimal number:
024587545
Given number is not valid

更新於: 13-Jul-2020

310 次瀏覽

開啟您的 職業

完成課程獲得證書

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