0

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.

1
  • 3
    Best advice: don't use regexp to read XML or HTML Commented Mar 14, 2012 at 18:43

2 Answers 2

3

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));
    }
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.