Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "\\d+" and "\\d++" in java regex [duplicate]

Tags:

java

regex

In java, what's the difference between "\\d+" and "\\d++"? I know ++ is a possessive quantifier, but what's the difference in matching the numeric string? What string can match "\\d+" but can't with "\\d++"? Possessive quantifier seems to be significant with quantifier ".*" only. Is it true?

like image 247
user2313900 Avatar asked Apr 24 '13 04:04

user2313900


People also ask

What is the meaning of regex \\ D?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).

What does \\ mean in Java regex?

Backslashes in Java. The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.

What is \\ w+ in Java regex?

\\w+ matches all alphanumeric characters and _ . \\W+ matches all characters except alphanumeric characters and _ . They are opposite.

What does \\ s+ in Java mean?

\\s - matches single whitespace character. \\s+ - matches sequence of one or more whitespace characters.


2 Answers

Possessive quantifiers will not back off, even if some backing off is required for the overall match.

So, for example, the regex \d++0 can never match any input, because \d++ will match all digits, including the 0 needed to match the last symbol of the regex.

like image 122
erickson Avatar answered Oct 24 '22 20:10

erickson


\d+ Means:
\d means a digit (Character in the range 0-9), and + means 1 or more times. So, \d+ is 1 or more digits.

\d++ Means from Quantifiers

This is called the possessive quantifiers and they always eat the entire input string, trying once (and only once) for a match. Unlike the greedy quantifiers, possessive quantifiers never back off, even if doing so would allow the overall match to succeed.

like image 36
Sumit Singh Avatar answered Oct 24 '22 19:10

Sumit Singh