如何在 Java 中打印与文件中的指定模式匹配的所有字符串



问题描述

如何打印与文件中的指定模式匹配的所有字符串?

解决方案

以下示例展示了如何利用 Util.regex 类的 Patternname.matcher() 方法打印与文件中的指定模式匹配的所有字符串。

import java.util.regex.*;
import java.io.*;

public class newfile {
   public static void main(String[] args) throws IOException {
      Pattern p1 = Pattern.compile("[A-Za-z][a-z]+");
      BufferedReader r = new BufferedReader(new FileReader("os.java"));
      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));
         }
      }
   }
}

结果

上面的代码示例将产生以下结果。

Android
java
ios
linux
java_regular_exp.htm
广告
© . All rights reserved.