8.3. Java中正则表达式用法举例

例 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);
}

        

详细代码可参考【已解决】Java的正则表达式Regex中,如何查找所有的匹配的项



例 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

        

详细代码可参考:

【已解决】Java中的正则表达式(java.util.regex)的替换

【已解决】Java的正则表达式java.util.regex中的命名的组(named group)