简体   繁体   中英

Is there a better way to extract name-value using group() in Matcher?

While extracting named data from input strings, one uses Matcher.group(String groupname) http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html

In the code below, receivedData is a hashmap that has the names of the groups. I have to iterate through it to get each name, and then call group(name). The hashmap has to be maintained separately and can potentially, names can be entered incorrectly or get out of sync with the names in the regex, since there are a large number of them.

String patternOfData = "On (day) I ate (mealName) at (restaurant) where they had a deal (entree) for only (price)";

After compiling the Pattern,

Pattern dataExtractionPattern = Pattern.compile(patternOfData);

Matcher matcher = dataExtractionPattern.matcher(receivedDataString);
                boolean b = matcher.matches();
                if (!b) {
                    return false;
                }
                for (String key : receivedData.keySet()) {
                    String dataValue;
                    dataValue = matcher.group(key);
                    receivedData.put(key, dataValue);
                }
                return true;

Wouldnt it be better if we had both name and value being returned together? Like Map.entry group();

Or is there another way that I can do this?

First of all, a named capturing group, newly available in Java 7, looks like (?< NAME > PATTERN ), where NAME is the name of the group and PATTERN is the pattern to match. So your example regex would be like On (?<day>\\S+) I ate (?<mealName>\\S+)...

If the pattern is fixed, then there is no reason you couldn't have a fixed list of group names. Then you could just build receivedData from scratch iterating through those group names, instead of needing it to already be set up with the correct keys.

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