java正则获取内容_Java利用正则表达式提取数据的方法

什么是正则表达式

正则表达式是一种可以用于模式匹配和替换的规范,一个正则表达式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)组成的文字模式,它 用以描述在查找文字主体时待匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。

Java利用正则表达式提取数据

Java正则表达式的用途很广,之前要用到将一大 3M 的 txt 文本切分成多个小文本,用 C# 写的话很简洁,代码也就二十几行,今天用 Java 写了一下,果然,Java 很罗嗦。

切分文件的代码就不贴了,主要贴一下怎么使用正则表达式将大字符串进行分组:

比如,现在有一个 endlist.txt 文本文件,内容如下:

1300102,北京市

1300103,北京市

1300104,北京市

1300105,北京市

1300106,北京市

1300107,北京市

1300108,北京市

1300109,北京市

1300110,北京市

1300111,北京市

1300112,北京市

1300113,北京市

1300114,北京市

1300115,北京市

1300116,北京市

1300117,北京市

1300118,北京市

1300119,北京市

七位数字代表手机号码的前七位,后面的汉字表示号码归属地。现在我要将这些内容按照 130 131 132...  开头分别写到 130.txt 131.txt 132.txt.....这些文件中。

public static void main(String args[]) {

File file = null;

BufferedReader br = null;

StringBuffer buffer = null;

String childPath = "src/endlist.txt";

String data = "";

try {

file = new File(childPath);

buffer = new StringBuffer();

InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");

br = new BufferedReader(isr);

int s;

while ((s = br.read()) != -1) {

buffer.append((char) s);

}

data = buffer.toString();

} catch (Exception e) {

e.printStackTrace();

}

Map> resultMap = new HashMap>();

for (int i = 0; i < 10; i++) {

resultMap.put("13" + i, new ArrayList());

}

Pattern pattern = Pattern.compile("(\\d{3})(\\d{4},[\u4e00-\u9fa5]*\\n)");

Matcher matcher = pattern.matcher(data);

while (matcher.find()) {

resultMap.get(matcher.group(1)).add(matcher.group(2));

}

for (int i = 0; i < 10; i++) {

if (resultMap.get("13" + i).size() > 0) {

try {

File outFile = new File("src/13" + i + ".txt");

FileOutputStream outputStream = new FileOutputStream(outFile);

OutputStreamWriter writer = new OutputStreamWriter(outputStream, "utf-8");

ArrayList tempList = resultMap.get("13" + i);

for (int j = 0; j < tempList.size(); j++) {

writer.append(resultMap.get("13" + i).get(j));

}

writer.close();

outputStream.close();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

第24行使用正则表达式  "(\\d{3})(\\d{4},[\u4e00-\u9fa5]*\\n)" 每个()中的内容为一组,索引从 1 开始,0表示整个表达式。所以这个表达式分为两组,第一组表示3个数字,第二组表示 4个数字加多个汉字加一个换行符。提取时如26-28行所示。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值