正则表达式匹配括号中的字符串

时间:2014-05-05 20:52:09

标签: regex

我正在构建一个必须从括号中提取字符串的正则​​表达式。这是一个示例字符串:

((?X is parent ?Y)(?X is child ?Z))

我需要得到字符串:'?X是父母?Y'还有'?X是孩子?Z'。这就是我创造的:

^(\((.*?)\))+$

问题是它只匹配第二个括号中的字符串。有人可以帮我改进表达式,以便它匹配括号中的两个字符串吗?

注意:括号可以包含任何内容,例如((AAA)(BBB))。在这种情况下,AAA'和' BBB'应该匹配。

谢谢。

2 个答案:

答案 0 :(得分:2)

根据您的评论,您似乎只想匹配括号内的任何内容,以便您可以使用:

String Sample1 = "((something)(world)(example))";
Pattern regex = Pattern.compile("\\(?\\((.*?)\\)\\)?");
Matcher regexMatcher = regex.matcher(Sample1);
while (regexMatcher.find()) {
System.out.print(regexMatcher.group(1));
    // something world example
} 

Demo

正则表达式解释

Match the character “(” literally «\(?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character “(” literally «\(»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is not a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “)” literally «\)»
Match the character “)” literally «\)?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»

答案 1 :(得分:1)

这似乎有效:

Pattern.compile("[\\(]{0,1}(\\((.*?)\\))")

感谢大家的回复和评论。