以下是将大于10的十六进制数与偶数长度匹配的正则表达式-
^(?=.{10,255}$)(?:0x)?\p{XDigit}{2}(?:\p{XDigit}{2})*$
哪里,
^:匹配句子的开头。
(?=。{10,255} $):字符串以10到255之间的字符结尾。
\ p {XDigit} {2}:两个十六进制字符。
(?:\ p {XDigit} {2})*:0个或更多序列的十六进制双字符。
$:匹配句子的结尾。
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(); } //接受英文字母的正则表达式 String regex = "^(?=.{10,255}$)(?:0x)?\\p{XDigit}{2}(?:\\p{XDigit}{2})*$"; //创建一个模式对象 Pattern pattern = Pattern.compile(regex); for (String hex : nums) { //创建一个Matcher对象 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
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"); } } }
Enter your name: 0x1234567890 Given name is valid
Enter a hexa-decimal number: 024587545 Given number is not valid