通过使用Regex打开文件来解析字符串行 [英] Parse a string line by opening a file using Regex

查看:95
本文介绍了通过使用Regex打开文件来解析字符串行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is the below text file(log.txt) I am opening and need to match each line using regular expressions.

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

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

So I wrote this regular expressions but it is not getting matched.

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();
        }
    }

任何建议都将受到赞赏。

Any suggestions will be appreciated.

推荐答案

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

The | is a special regex symbol which means 'or'. So, you have to escape it.

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

这篇关于通过使用Regex打开文件来解析字符串行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆