您的位置:首页 > 编程语言 > Java开发

【JAVA正则表达式使用方法】

2013-09-30 10:33 609 查看
一般正则表达式如果过于麻烦,转换成字符串还不如直接写到文件里让程序读取文件

package com.gaohaixiang.正则表达式;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Ip和端口 {
public static void readTxtFile(String filePath) {
String rex = null;
try {
String encoding = "GBK";

File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
rex = bufferedReader.readLine();
Pattern p = Pattern.compile(rex);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
Matcher m = p.matcher(lineTxt);
if (m.find()) {
String s = m.group(0).replaceAll(":", "\n").replaceAll(
"@", "\n");
System.out.print(s);

}
}

} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}

public static void main(String[] args) {
String filePath = "D:\\123.txt";
// "res/";s
readTxtFile(filePath);
}
}


123.txt

((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)(\.((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)){3}
1.34.181.22:110@HTTP#台湾省中华电信股份有限公司
1.63.18.22:8080@HTTP#黑龙江省鸡西市联通
1.214.200.211:80@HTTP#韩国
2.181.177.7:8080@HTTP#伊朗
270010101@qq.com
5.199.166.250:7808@HTTP#立陶宛
14.1.38.247:8080@HTTP#新西兰
27.17.61.117:9797@HTTP#湖北省武汉市电信
27.131.251.102:80@HTTP#印度尼西亚
36.32.18.62:8080@HTTP#安徽省合肥市联通
37.46.197.58:3128@HTTP#荷兰
37.159.192.162:3128@HTTP#意大利
41.32.136.74:8080@HTTP#埃及
41.78.26.225:8080@HTTP#肯尼亚
41.78.145.9:8080@HTTP#加纳
41.89.130.6:3128@HTTP#肯尼亚


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JAVA JDK 正则表达式