Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern.compile("\\[.+?\\]");

Tags:

java

regex

In this statement, taken from the Pagerank source code:

Pattern.compile("\\[.+?\\]");

What does the pattern mean? I have tried studying it, it says 2 slashes mean a single slash, but what are the .+??

like image 405
user1291453 Avatar asked Mar 26 '12 21:03

user1291453


1 Answers

This string literal:

"\\[.+?\\]"

means this string:

\[.+?\]

So this expression:

Pattern.compile("\\[.+?\\]");

means this regex:

\[.+?\]

which means "a literal [, followed by one or more characters — preferably as few as possible — followed by ]". (. means "any character other than newline"; +? means "one or more of what I just said, and preferably as few as possible".) So overall, the regex matches [____], where ____ can be anything that doesn't contain a newline, as long as it's at least one character long; and where ____ won't (normally) contain a ] except possibly as the very first character.

For more information about Pattern and regexes in Java, see the documentation for the Pattern class.

like image 192
ruakh Avatar answered Sep 25 '22 13:09

ruakh