Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ".+" and ".+?"

Tags:

regex

Can someone please explain the difference between .+ and .+?

I have the string: "extend cup end table"

  1. The pattern e.+d finds: extend cup end
  2. The pattern 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.

like image 853
nakul Avatar asked Jan 08 '13 11:01

nakul


People also ask

What's the difference between single and double quotation marks?

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.

What is the difference between single and double inverted commas?

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).

What are single quotation marks used for?

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.

What is the difference between quotation marks and a single?

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.


1 Answers

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.
like image 68
NPE Avatar answered Sep 23 '22 08:09

NPE