Reputation: 345
I'm building a regular expression which have to extract strings from brackets. This is an example string:
((?X is parent ?Y)(?X is child ?Z))
I need to get strings: '?X is parent ?Y' and also '?X is child ?Z'. This is what I've created yet:
^(\((.*?)\))+$
The problem is that it matches only the string in the second bracket. Could anybody help me to improve the expression so that it matches both strings in brackets?
Note: brackets can contain any content, like ((AAA)(BBB)). In this case 'AAA' and 'BBB' should be matched.
Thanks forward.
Upvotes: 0
Views: 1775
Reputation: 99071
Based on your comments, it seems that you just want to match anything inside the brackets, for that you can use:
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
}
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) «?»
Upvotes: 2
Reputation: 345
This seems to work:
Pattern.compile("[\\(]{0,1}(\\((.*?)\\))")
Thanks all for replies and comments.
Upvotes: 1