使用scanner useDelimiter解析文本

Bri*_*ian 5 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>
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

我试图使用扫描仪和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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

v1= 2008-10-07>text entered by user v2=Ted Parlor> 
Run Code Online (Sandbox Code Playgroud)

我想要的是:

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
Run Code Online (Sandbox Code Playgroud)

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

pol*_*nts 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这打印:

[2008-10-07|text entered by user|Ted Parlor]
[2008-11-26|additional text entered by user|Ted Parlor]
[2008-11-28||Parlor Ted]
Run Code Online (Sandbox Code Playgroud)

也可以看看