Java 通过使用正则表达式打开文件来解析字符串行
这是我正在打开的下面的文本文件(log.txt),需要使用正则表达式匹配每一行Java 通过使用正则表达式打开文件来解析字符串行,java,regex,Java,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) {
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 = "(.*?)\\|(.*?)\\|(.*?)\\|(.*?)";
|
是一个特殊的正则表达式符号,表示“或”。所以,你必须逃避它
public static String pattern = "(.*?)\\|(.*?)\\|(.*?)\\|(.*?)";
您可以为此大大简化正则表达式。因为数据看起来是管道分隔的,所以应该只在管道字符上进行拆分。您将得到一个字段数组,可以根据需要进一步解析这些字段:
String[] fields = line.split("\\|");
您可以为此大大简化正则表达式。因为数据看起来是管道分隔的,所以应该只在管道字符上进行拆分。您将得到一个字段数组,可以根据需要进一步解析这些字段:
String[] fields = line.split("\\|");