在Java编程中,如何从文件中打印与给定模式匹配的所有字符串?
以下示例显示了如何使用Util.regex
类的Patternname.matcher()
方法从文件中打印与给定模式匹配的所有字符串。
package com.yiibai;
import java.util.regex.*;
import java.io.*;
public class PatternMatchingFromFile {
public static void main(String[] args) throws IOException {
Pattern p1 = Pattern.compile("[A-Za-z][a-z]+");
BufferedReader r = new BufferedReader(new FileReader("newfile.txt"));
String line;
while ((line = r.readLine()) != null) {
Matcher m = p1.matcher(line);
while (m.find()) {
System.out.println(m.group(0));
int s1 = m.start(0);
int e1 = m.end(0);
//System.out.println(line.substring(s1, e1));
}
}
}
}
Java
上述代码示例将产生以下结果 -
java
tutorial
android
java
frameworks
javascript
ajax
core
java
sql
python
php
language
etc
原文地址:https://www.cnblogs.com/borter/p/9617147.html
时间: 2024-10-09 07:55:35