fredoverflow
fredoverflow

Reputation: 263098

help with regex

From the string [foo](bar) I want to extract the foo and the bar part:

Pattern p = Pattern.compile("\\[(.*)\\]\\((.*)\\)");
String input = "[foo](bar)";
assert p.matcher(input).matches();
String[] a = ???   // should be initialized to {"foo", "bar"}

What do I write in the fourth line to obtain foo and bar from the input?

Upvotes: 2

Views: 108

Answers (2)

manojlds
manojlds

Reputation: 301087

I would say a regex like below is easier to handle and extend:

[\[\(](.*?)[\]\)]

Upvotes: 0

jjnguy
jjnguy

Reputation: 138864

This should get you close to where you wanna be:

Pattern p = Pattern.compile("\\[(.*)\\]\\((.*)\\)");
String input = "[foo](bar)";
Matcher m = p.matcher(input);
if (m.find()){
    String[] a = { m.group(1), m.group(2) }; 
}

Essentially, you will create a Matcher. Then use find() to locate the match. Then you will use the groups to find the things that were matched inside of the parenthesis.

Upvotes: 4

Related Questions