Mark13426
Mark13426

Reputation: 2639

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.

Upvotes: 0

Views: 1886

Answers (2)

dule
dule

Reputation: 18168

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

Upvotes: 3

rapadura
rapadura

Reputation: 5300

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.

Upvotes: 2

Related Questions