正则表达式并在文本文件中查找

时间:2014-11-27 13:30:44

标签: java regex

我有这段代码:

package ggg;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;

public class regex {
     public static void main( String args[] ){

          // String to be scanned to find the pattern.
          String line = "This order was placed FRO-DDA-6666666 %10.25 %10.12 FRO-DDA-8888888 for QT3000! OK?";
          String pattern = "\\d+\\.\\d{2}";
          String pattern2 = "\\d{7}";


          // Create a Pattern object
          Pattern r = Pattern.compile(pattern);
          Pattern t = Pattern.compile(pattern2);

          // Now create matcher object.
          Matcher m = r.matcher(line);
          Matcher g = t.matcher(line);
          try {
          PrintWriter writer = new PrintWriter("C:\\Users\\John\\workspace\\ggg\\src\\ggg\\text.txt", "UTF-8");
          for (int i = 1; m.find() && g.find(); i++) {
             writer.println(g.group(0)+"->"+m.group(0));
          }
          writer.close();
          } catch (IOException ex) {}
       }

}

结果是:
6666666-> 10.25
8888888-> 10.12

我想写一个简单的代码来读取text.txt文件,如果此文件中存在“8888888”,那么打印“8888888->”的前面是什么,我该怎么办?
例如,在我们的结果中,10.12是888888->

的前面

1 个答案:

答案 0 :(得分:1)

在构建文件后将其添加到您的代码中:

    BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\John\\workspace\\ggg\\src\\ggg\\text.txt"));
    String myLine;
    while ((myLine = br.readLine()) != null) {
       if(myLine.contains("8888888"))
           System.out.println(myLine.substring(myLine.indexOf(">")+1));
    }
    br.close();