简体   繁体   中英

Extract key-value pairs using a Java regex

I have a string with the following format: <element>Key:Value</element>

Similar strings are appended to one another to create a compound string, so if there are three strings, I'd have the following format: <element>Key:Value</element><element>Key:Value</element><element>Key:Value</element>

There are no characters between two elements.

I want to write a regex expression so I can extract the key-value pairs and put them in a HashMap. The mapping part is easy, but I don't know how to do the regex part.

Aye, as mentioned, an XML parser would probably be more appropriate here, but if you want to do with a regex:

    String str = "<element>Key1:Value1</element><element>Key2:Value2</element><element>Key2:Value2</element>";
    final Pattern p = Pattern.compile("<element>(.*?):(.*?)</element>");

    Matcher m = p.matcher(str);
    while (m.find()) {
        System.out.print("Key=" + m.group(1));
        System.out.println("; Value=" + m.group(2));
    }

Don't do it with regexp, use a real XML parser and extract the contents of the element erm elements, and use the regexp on that, or a simple string.split(":")

Like,

List<XMLElements> els = XMLParser.parse(yourXmlFile); 
then for each XMLElement is element in els element.split(":") and take [0] for key and [1] for value.

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