Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

* and ** difference

Tags:

java

regex

What is difference between * and **? Why .** is not compiling while using pattern.compile(".**");?

like image 632
Squeez Avatar asked Oct 17 '25 14:10

Squeez


1 Answers

See the Java Quantifiers reference:

Greedy  Reluctant   Possessive  Meaning
X?      X??         X?+         X, once or not at all
X*      X*?         X*+         X, zero or more times
X+      X+?         X++         X, one or more times
X{n}    X{n}?       X{n}+       X, exactly n times
X{n,}   X{n,}?      X{n,}+      X, at least n times
X{n,m}  X{n,m}?     X{n,m}+     X, at least n but not more than m times

There is no ** quantifier. When you use + after +, * or ? (or even {n,m}), you can create a possessive quantifier (see the table above), but adding a * quantifier after a * is considered a user error.

That is why .* would match 0+ characters other than a newline (without the Pattern.DOTALL modifier) and .** throws an exception.

Note that online regex testers also warn you of this problem: Dangling meta character '*' near index 2 .** ^ (same warning appears at OCPSoft regex tester).

like image 189
Wiktor Stribiżew Avatar answered Oct 20 '25 02:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!