java中的正則表達式的簡單實用demo
需要注意項:
- java中的反斜線需要兩個
- 在獲取配置項是需要先調用matcher.matches() 和matcher.find()中的一個方法來判斷 匹配中了沒有
- 表達式的初始化可以放在成員變量中, 沒必要重複初始化
- 可以先在一些在線正在表達式網站上面先調試好正則
public static void main(String[] args) {
//可以把這句放在類的成員變量中, 因爲每次生成對象耗費資源。 並且正則表達式是線程安全的
//具體的正在表達式的知識,請參考https://www.runoob.com/regexp/regexp-metachar.html
//建議先在在線正則表達式網站中調試好表達式, 再拷貝到idea中,idea中字符串拷貝會自動給你加上兩個\\,十分方便
Pattern pattern = Pattern.compile(".*副本(\\((\\d+)\\))?$");
//開始正則匹配
Matcher matcher = pattern.matcher("文件名稱副本(2)");
//在獲取具體的正則表達式的時候,請先調用下matcher.matches() 和matcher.find()中的一個方法。 不然會獲取失敗
if (matcher.matches()) {
// 這個groupCount返回的數字,表示的子正則(就是上面正則中的括號內)匹配中的個數。
//所以如果要遍歷上面的正則匹配的結果,可以在這個i上加1後循環
int count = matcher.groupCount();
System.out.println(count);
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
運行結果: