Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Matching Java Regex - "One-or-more" operator

Tags:

java

regex

How is the "one-or-more" operator used in regex for Java? For example, I want to match this:

( (a) (b) (c) ) - matches

( (a) ) - matches

where a,b,c are any characters or digits

The basic description of this expression is sets of parentheses within a set of parentheses that contains all of the sets separated by one white space

like image 967
Aneem Avatar asked Feb 25 '13 03:02

Aneem


1 Answers

You want something like \((\(\w*\))+\)

To make it clearer how it works, expand it a bit visually:

\(    # outer bracket
(     # start of group
\(    # inner bracket
\w*   # 0 or more word characters ([0-9a-zA-Z_])
\)    # inner bracket
)     # end of group
+     # and we do that group 1 or more times
\)    # outer bracket

Explanation: If you apply * or + or ? to something that was just in (unescaped) brackets, then it is applied to the entire contents of the brackets instead of to just one element.

Whenever I have a regex question I look it up in http://www.regular-expressions.info/reference.html

like image 162
Patashu Avatar answered Oct 19 '22 01:10

Patashu