帮助正则表达式

时间:2011-05-31 18:54:07

标签: java regex

从字符串[foo](bar)我想提取foobar部分:

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

我在第四行写什么来从输入中获取foobar

2 个答案:

答案 0 :(得分:4)

这应该让你接近你想要的地方:

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

基本上,您将创建一个Matcher。然后使用find()找到匹配项。然后,您将使用这些组来查找括号内匹配的内容。

答案 1 :(得分:0)

我想说下面的正则表达式更易于处理和扩展:

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