正則表示式提取專案中所有帶IP的網址
阿新 • • 發佈:2019-01-30
假如現在需要在整個專案中搜索所有帶IP的網址,例如webService釋出地址呀這樣的,
隨便舉個栗子
http://127.0.0.1:8080/XXXXX/services/AService
那怎樣通過正則表示式來搜尋整個專案的這種網址呢?用正則表示式匹配就好啦。
第一步,掃描專案目錄下所有檔案
public void scanFile(File file) {
File[] fileLists = file.listFiles();
Set<String> finalFiles = new HashSet<String>();
for (int i = 0; i < fileLists.length; i++) {
// 判斷是否是檔案
if (fileLists[i].isFile()) {
// 如果是檔案就匹配http地址
findStr(fileLists[i], finalFiles);
} else {//如果是資料夾
scanFile(fileLists[i]);
}
}
for (String string : finalFiles) {
System.out.println(string);
}
}
第二步,正則匹配
public void findStr(File file, Set<String> finalFiles) {
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String line;
while ((line = bReader.readLine()) != null) {
boolean flag = Pattern.matches(".*http://([0-9]{1,3}.){3}([0-9]{1,3}).*", line);
if (flag) {
// 去掉前面多餘的字串
int index = line.indexOf("http://");
String addr = line.substring(index);
finalFiles.add(addr);
}
}
bReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
第三步,主函式
public static void main(String[] args) {
TestFindAddress t = new TestFindAddress();
String filePath = "D://java//project//testPattern";
File file = new File(filePath);
t.scanFile(file);
}
好啦~~~