Can someone please explain the difference between .+
and .+?
I have the string: "extend cup end table"
e.+d
finds: extend cup end
e.+?d
finds: extend
and end
I know that +
is one or more and ?
is one or zero. But I am not able to understand how does it work.
General Usage Rules In America, Canada, Australia and New Zealand, the general rule is that double quotes are used to denote direct speech. Single quotes are used to enclose a quote within a quote, a quote within a headline, or a title within a quote.
Double quotation marks (in British English) are used to indicate direct speech within direct speech (use single inverted commas for direct speech and double quotation marks to enclose quoted material within).
Single quotation marks are also known as 'quote marks', 'quotes', 'speech marks' or 'inverted commas'. Use them to: show direct speech and the quoted work of other writers. enclose the title of certain works.
The use of single and double quotation marks when quoting differs between US and UK English. In US English, you must use double quotation marks. Single quotation marks are used for quotes within quotes.
Both will match any sequence of one or more characters. The difference is that:
.+
is greedy and consumes as many characters as it can..+?
is reluctant and consumes as few characters as it can.See Differences Among Greedy, Reluctant, and Possessive Quantifiers in the Java tutorial.
Thus:
e.+d
finds the longest substring that starts with e
and ends with d
(and contains at least one character in between). In your example extend cup end
will be found.e.+?d
find the shortest such substring. In your example, extend
and end
are two such non-overlapping matches, so it finds both.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With