正則表達式中分組說明
正則表達式可以通過」()」來進行分組,更專業的表達就是捕獲組,每個完整的」()」可以分為一組,同時,」()」中還可以嵌套」()」,即組之間還可以存在更小的組,以此類推。而編號為0的組,則是正則表達式匹配到的整體,這個規則只要支持正則表達式中捕獲組的語言基本上都適用。
捕獲組就是把正則表達式中子表達式匹配的內容,保存到內存中以數字編號或顯式命名的組裡,方便後面引用。當然,這種引用既可以是在正則表達式內部,也可以是在正則表達式外部。
Java程序也可以正則表達式完美融入到程序中,而且非常好用,下面介紹幾種不同的用法,可以根據自己應用需要進行選擇。
普通捕獲組編號規則
如果沒有顯式為捕獲組命名,即沒有使用命名捕獲組,那麼需要按數字順序來訪問所有捕獲組。在只有普通捕獲組的情況下,捕獲組的編號是按照「(」出現的順序,從左到右,從1開始進行編號的 。
正則表達式分組舉例:(\d{4})-(\d{2}-(\d\d))
1、在正則表達式中使用組
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
// Prepare regular expression. A group of 3 digits followed by 7 digits.
String regex = "\\b(\\d{3})\\d{7}\\b";
String source = "1111111111, 1111111, and 1111111111";
// Compile the regular expression
Pattern p = Pattern.compile(regex);
// Get Matcher object
Matcher m = p.matcher(source);
// Start matching and display the found area codes
while(m.find()) {/** 來 自 時 代 J a v a - nowjava.com**/
// Display the phone number and area code.
// group 1 captures first 3 digits of match,
// whereas group 0 will have the entire phone number.
// The matched text can be obtained using m.group() or m.group(0)
String phone = m.group();
String areaCode = m.group(1);
System.out.println("Phone: " + phone + ", Area Code: " + areaCode);
}
}
}
2、在正則表達式中使用命名組
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {/**來 自 n o w j a v a . c o m**/
public static void main(String[] args) {
// Prepare the regular expression
String regex = "\\b(?<areaCode>\\d{3})(?<prefix>\\d{3})(?<lineNumber>\\d{4})\\b";
// Reference first two groups by names and the thrd oen as its number
String replacementText = "(${areaCode}) ${prefix}-$3";
String source = "1111111111, 1111111, and 1111111111";
// Compile the regular expression
Pattern p = Pattern.compile(regex);
// Get Matcher object
Matcher m = p.matcher(source);
// Replace the phone numbers by formatted phone numbers
/**
來 自 時 代 J a v a 公 眾 號
**/
String formattedSource = m.replaceAll(replacementText);
System.out.println("Text: " + source);
System.out.println("Formatted Text: " + formattedSource);
}
}
3、返回替換文本中引用組
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String regex = "\\b(\\d{3})(\\d{3})(\\d{4})\\b";
String replacementText = "($1) $2-$3";
String source = "1111111111, 1111111, and 1111111111";
// Compile the regular expression
Pattern p = Pattern.compile(regex);
// Get Matcher object
Matcher m = p.matcher(source);
/** from N o w J a v a . c o m - 時代Java**/
// Replace the phone numbers by formatted phone numbers
String formattedSource = m.replaceAll(replacementText);
System.out.println("Text: " + source );
System.out.println("Formatted Text: " + formattedSource );
}
}