简体   繁体   中英

Java Regex Pattern for getting text between digits in parentheses

I have the following sample of Text, with new lines:

(2) County
HAW
(3) District
PN
(4) Beat
831
(5) Watch
2
(6) Date/Time/Day Occurred
11/19/2019 14:47 TU
(7) Date/Time/Day Reported
11/19/2019 14:47 TU

I am trying to come up with a RegEx pattern so that I could put the text, extracted from a String with new lines into a HashMap with a key for each new line, and iteratively be able to put the text strings into the map something like this:

Map<String, String> m = new HashMap<String,String>();
m.put("(2) County","HAW"
m.put("(3) District","PN"
m.put("(4) Beat","831"
m.put("(6) Date/Time/Day Occurred","11/19/2019 14:47 TU"
m.put("(5) Watch","2"
m.put("(7) Date/Time/Day Reported","11/19/2019 14:47 TU"

Getting closer, Can this be optimized ?

Pattern pattern = Pattern.compile("\\(\\d\\)(.*)");
        String INPUT   =  "(2) County\n" + 
                "HAW\n" + 
                "(3) District\n" +
                "PA\n"  ;

        String[] result = pattern.split(INPUT);
        Matcher matcher = pattern.matcher(INPUT);


        final Map<String, String> matches = new HashMap<>();
        int i = 1;
        while (matcher.find()) {
            matches.put(matcher.group(0).trim(),result[i].trim());
            i++;
        }


        for (Map.Entry<String,String> entry : matches.entrySet())  
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM