5

希望解析以下文本文件:
示例文本文件:

<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

任何可以让我分别提取所有三个字符串的帮助将不胜感激。

4

1 回答 1

6

您可以\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]

也可以看看

于 2010-05-29T16:59:28.337 回答