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