public class CodeTest { public static void main(String[] args) { String regex = "D:\\\\mycode\\\\test\\\\mytext_([0-9]{8}).txt"; String fileName_1 = "D:\\mycode\\test\\mytext_20191122.txt"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(fileName_1); if(m.find()){ System.out.println("target :"+m.group(1)); } } }
Pattern -》java代碼中的正則表達式對象
p.matcher(str)-》str是需要被匹配的文本內容,並返回一個Matcher 對象,對象中包含衆多返回結果在其中。
m.find()-》返回匹配結果布爾(true|false)值.
m.groupCount()-》用以返回匹配部分字符串數組。注意需要返回的部分必須通過()包裹起來,作爲一個整體。
m.group(1)-》返回想要提取的字符串。
matcher.group(int)方法即可實現java正則表達式從文本中提取內容。但是核心重點是需要被提取的部分必須在寫正則表達式的時候用小括號包裹起來。這個在很多的資源中都沒講。