Parsing text using the useDelimiter scanner

Looking at the analysis of the following text file:
Example text file:

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

I would like to parse the above text to have three variables:

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

I tried using a scanner and using Delimiter, however, I had a problem with how to set this to get the results as above. Here is my first attempt:

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

The results are as follows:

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

I want:

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

Any help that would allow me to extract all three lines separately would be greatly appreciated.

+5
source share
1 answer

\s*[<>]\s* . < > .

< > , , (.. no 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 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]

.

+7

All Articles