AdSense

網頁

2020/5/6

Java Regex 檢查字串是否只含hex字元 check hex char

Java 使用regex(正則表示式, Regular expression)檢查字串是否只含hex字元,也就是只含0123456789ABCDEF

String s1 = "0123456789ABCDEF";
String s2 = "0123456789ABCDEFG";

String regexCheckContainHexCharOnly = "^[0-9A-Fa-f]+$";

// String.matches(String regex)
boolean r1 = s1.matches(regexCheckContainHexCharOnly);
boolean r2 = s2.matches(regexCheckContainHexCharOnly);

System.out.println(r1); // true
System.out.println(r2); // false


// java.util.regex.Pattern
Pattern pattern = Pattern.compile(regexCheckContainHexCharOnly);
r1 = pattern.matcher(s1).matches();
r2 = pattern.matcher(s2).matches();

System.out.println(r1); // true
System.out.println(r2); // false

沒有留言:

AdSense