通过使用Regex打开文件来解析字符串行

这是我打开的下面的文本文件(log.txt),需要使用正则表达式匹配每一行。

Jerty|gas|petrol|2.42 Tree|planet|cigar|19.00 Karie|entertainment|grocery|9.20 

所以我写了这个正则表达式,但没有得到匹配。

 public static String pattern = "(.*?)|(.*?)|(.*?)|(.*?)"; public static void main(String[] args) { File file = new File("C:\\log.txt"); try { Pattern regex = Pattern.compile(pattern); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Matcher m = regex.matcher(line); if(m.matches()) { System.out.println(m.group(1)); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

任何建议将不胜感激。

| 是一个特殊的正则表达式符号,意思是’或’。 所以,你必须逃脱它。

 public static String pattern = "(.*?)\\|(.*?)\\|(.*?)\\|(.*?)"; 

你可以大大简化正则表达式。 由于数据看起来是以管道分隔的,因此您应该在管道字符上进行拆分。 您将最终获得一系列字段,您可以根据需要进一步解析:

 String[] fields = line.split("\\|");