例 8.1. 匹配所有的某种格式的字符串
想要匹配:
11A11、22A22、33A33、44B44、55B55
中的每个值,并打印出来,然后对应的Java代码为:
String digitNumStr = "11A11、22A22、33A33、44B44、55B55"; //String digitNumStr = "11A11"; Pattern digitNumP = Pattern.compile("(?<twoDigit>\\d{2})[A-Z]\\k<twoDigit>"); Matcher foundDigitNum = digitNumP.matcher(digitNumStr); // Find all matches while (foundDigitNum.find()) { // Get the matching string String digitNumList = foundDigitNum.group(); System.out.println(digitNumList); }
例 8.2. 带命名的组去替换单个字符串
想要将字符串
aa/haha.exe
中的前面部分去掉,只保留后面部分,即:
haha.exe
则用的java代码为:
String filenameStr = "aa/haha.exe"; //named group only support after Java 7 //here is my java version: //Java: 1.7.0_09; Java HotSpot(TM) 64-Bit Server VM 23.5-b02 Pattern filenameP = Pattern.compile("^.+/(?<filenamePart>.+)$"); Matcher filenameMatcher = filenameP.matcher(filenameStr); boolean foundFilename = filenameMatcher.matches(); System.out.println(filenameMatcher); System.out.println(foundFilename); String onlyFilename = filenameMatcher.replaceFirst("${filenamePart}"); System.out.println(onlyFilename);
输出为:
java.util.regex.Matcher[pattern=^.+/(?<filenamePart>.+)$ region=0,11 lastmatch=aa/hahatrue] true haha.exe
详细代码可参考: