1

I'm looking for a Regex pattern that matches the following, but I'm kind of stumped so far. I'm not sure how to grab the results of the two groups I want, marked by id, and attr.

Should match:

  • account[id].attr
  • account[anotherid].anotherattr

These should respectively return id, attr,
and anotherid, anotherattr

Any tips?

3
  • Can we see your attempts to solve this task? How do you think regex which can match account[xxx].yyy may look like? Commented Sep 4, 2014 at 15:59
  • 1
    it's seems unclear. Please explain a bit more. Commented Sep 4, 2014 at 15:59
  • I guess I just want to match account[sometext].moretext and grab the sometext and moretext fields. It seems possible! Commented Sep 4, 2014 at 16:18

1 Answer 1

2

Here's a complete solution mapping your id -> attributes:

String[] input = {
        "account[id].attr",
        "account[anotherid].anotherattr"
};
//                           | literal for "account"
//                           |      | escaped "["
//                           |      |  | group 1: any character 
//                           |      |  |   | escaped "]"
//                           |      |  |   |  | escaped "."
//                           |      |  |   |  |  | group 2: any character
Pattern p = Pattern.compile("account\\[(.+)\\]\\.(.+)");
Map<String, String> output = new LinkedHashMap<String, String>();
// iterating over input Strings
for (String s: input) {
    // matching
    Matcher m = p.matcher(s);
    // finding only once per input String. Change to a while-loop if multiple instances
    // within single input
    if (m.find()) {
        // back-referencing group 1 and 2 as key -> value
        output.put(m.group(1), m.group(2));
    }
}
System.out.println(output);

Output

{id=attr, anotherid=anotherattr}

Note

In this implementation, "incomplete" inputs such as "account[anotherid]." will not be put in the Map as they don't match the Pattern at all.

In order to have these cases put as id -> null, you only need to add a ? at the end of the Pattern.

That will make the last group optional.

Sign up to request clarification or add additional context in comments.

3 Comments

hmm snag.gy/ZHHzk.jpg shows that it doesn't match... otherwise looks good!!
@phouse512 Quoth the server, 404. Although testing your Java Patterns with Java has the clear advantage over web tools of actually seeing it matched with the Java regex engine.
@phouse512 same answer (minus the 404): probably a different engine, or different way to handle escapes (i.e. single vs double).

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.