Java模式匹配
如何打印所有从一个文件中的字符串匹配给定模式?
解决方法
下面的示例显示了如何打印所有从文件与Util.regex类的Patternname.matcher()方法匹配给定模式的字符串。
import java.util.regex.*; import java.io.*; public class ReaderIter { public static void main(String[] args) throws IOException { Pattern patt = Pattern.compile("[A-Za-z][a-z]+"); BufferedReader r = new BufferedReader (new FileReader("ReaderIter.java")); String line; while ((line = r.readLine()) != null) { Matcher m = patt.matcher(line); while (m.find()) { System.out.println(m.group(0)); int start = m.start(0); int end = m.end(0); Use CharacterIterator.substring(offset, end); System.out.println(line.substring(start, end)); } } } }
结果
上面的代码示例将产生以下结果。
Ian Darwin http www darwinsys com All rights reserved Software written by Ian Darwin and others