使用scanner useDelimiter解析文本

时间:2010-05-29 16:49:45

标签: java regex string parsing java.util.scanner

想要解析以下文本文件:
示例文本文件:

<2008-10-07>text entered by user<Ted Parlor><2008-11-26>additional text entered by user<Ted Parlor>

我想解析上面的文本,以便我可以有三个变量:

v1 = 2008-10-07
v2 = text entered by user
v3 = Ted Parlor
v1 = 2008-11-26
v2 = additional text entered by user
v3 = Ted Parlor

我试图使用扫描仪和useDelimiter,但是,我有关于如何设置它以获得如上所述结果的问题。这是我的第一次尝试:

import java.io.*;
import java.util.Scanner;

public class ScanNotes {
    public static void main(String[] args) throws IOException {
        Scanner s = null;
        try {
            //String regex = "(?<=\\<)([^\\>>*)(?=\\>)";
            s = new Scanner(new BufferedReader(new FileReader("cur_notes.txt")));
            s.useDelimiter("[<]+");

            while (s.hasNext()) {
                String v1 = s.next();
                String v2= s.next();
                System.out.println("v1= " + v1 + " v2=" + v2);
            }
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
}

结果如下:

v1= 2008-10-07>text entered by user v2=Ted Parlor> 

我的愿望是:

v1= 2008-10-07 v2=text entered by user v3=Ted Parlor
v1= 2008-11-26 v2=additional text entered by user v3=Ted Parlor

任何帮助我分别提取所有三个字符串的帮助都将非常感激。

1 个答案:

答案 0 :(得分:7)

您可以使用\s*[<>]\s*作为分隔符。也就是说,<>中的任何一个,包含前后任何空格。

为此,输入中不得有任何<>,而不是用于标记输入中的日期和用户字段的输入(即无I <3 U!!在消息中。)

此分隔符允许条目中的空字符串部分,但它也会在任意两个条目之间留下空字符串标记,因此必须手动将其丢弃。

import java.util.Scanner;

public class UseDelim {
    public static void main(String[] args) {
        String content = " <2008-10-07>text entered by user <Ted Parlor>"
        + "   <2008-11-26>  additional text entered by user <Ted Parlor>"
        + "   <2008-11-28><Parlor Ted>  ";
        Scanner sc = new Scanner(content).useDelimiter("\\s*[<>]\\s*");
        while (sc.hasNext()) {
            System.out.printf("[%s|%s|%s]%n",
                sc.next(), sc.next(), sc.next());

            // if there's a next entry, discard the empty string token
            if (sc.hasNext()) sc.next();
        }
    }
}

打印:

[2008-10-07|text entered by user|Ted Parlor]
[2008-11-26|additional text entered by user|Ted Parlor]
[2008-11-28||Parlor Ted]

另见