Hows does the Regular Expression: /.+?/ work? - regex

How would the '.+?' regular expression work? Is the .+ part matching anything written, and the ? part saying it can either be there or not? So, for example, this regular expression would match:
'cat'
'' (ie, nothing written, just the empty string)

The "+?" is not a "+" quantifier followed by a "?" quantifier. Instead the "?" modifies the "+" to perform a "lazy" or "non greedy" match, meaning that the least number of characters that match is already sufficient.
So a "a+?" regex would match just a single "a" in "caaat".

Besides what Hans Kesting already said, a lazy multiplier will do the exact oposite of the normal greedy multipliers: The possible match is kept as small as possible and the rest of the regular expression is tested.
So if you’re having the string aaba and test the regular expression a.*b on it, the internal processing steps would be as follows:
a in a.*b matches aaba
.* in a.*b matches aaba, and since .* is greedy
.* then matches aaba
.* then matches aaba
b in a.*b fails as there is no letter left
backtracking goes one step back and .* will now only match bb in aaba
b in a.*b still fails on aaba
backtracking goes one step back and .* now matches only b in aaba
b in a.*b now matches b in aaba and we’re done.
So the full match is aaba.
If we do the same with a lazy multiplier (a.*?b), the processing will do the oposite, try to match the least possible characters as possible:
a in a.*?b matches aaba
.* in a.*?b matches nothing (* = zero or more repetitions), and since .* is declared as lazy (.*?), the rest of the regular expression is tested
b in a.*?b fails on aaba
backtracking will try to increase the match of .*
.* matches now aaba
b in a.*?b matches aaba and we’re done.
So the full match if aaba.

+? (lazy plus)
Repeats the previous item once or
more. Lazy, so the engine first
matches the previous item only once,
before trying permutations with ever
increasing matches of the preceding
item.
/".+?"/ matches "def" (and "ghi") in abc "def" "ghi" jkl, while /".+"/ matches "def" "ghi".
You can find more info here

There is documentation on how Perl handles these quantifiers perldoc perlre.
By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a "?". Note that the meanings don't change, just the "greediness":
*? Match 0 or more times, not greedily
+? Match 1 or more times, not greedily
?? Match 0 or 1 time, not greedily
{n}? Match exactly n times, not greedily
{n,}? Match at least n times, not greedily
{n,m}? Match at least n but not more than m times, not greedily
By default, when a quantified subpattern does not allow the rest of the overall pattern to match, Perl will backtrack. However, this behaviour is sometimes undesirable. Thus Perl provides the "possessive" quantifier form as well.
*+ Match 0 or more times and give nothing back
++ Match 1 or more times and give nothing back
?+ Match 0 or 1 time and give nothing back
{n}+ Match exactly n times and give nothing back (redundant)
{n,}+ Match at least n times and give nothing back
{n,m}+ Match at least n but not more than m times and give nothing back
For instance,
'aaaa' =~ /a++a/
will never match, as the a++ will gobble up all the a 's in the string and won't leave any for the remaining part of the pattern. This feature can be extremely useful to give perl hints about where it shouldn't backtrack. For instance, the typical "match a double-quoted string" problem can be most efficiently performed when written as:
/"(?:[^"\\]++|\\.)*+"/
as we know that if the final quote does not match, backtracking will not help. See the independent subexpression (?>...) for more details; possessive quantifiers are just syntactic sugar for that construct. For instance the above example could also be written as follows:
/"(?>(?:(?>[^"\\]+)|\\.)*)"/
link

inevitably, the regex is going to look for at least one character. I've come across case where an empty string wouldn't pass that test already, it would be better to use .*? or (.*)? instead, sometimes you have to specify the part of the string which may be null in braces before the question mark, it helps. E.g. \d{6}? will yield a wrong result, whereas if I had said (\d{6})? in a string say for example:
preg_match("/shu\.(\d{6})?/", "shu.321456")
this will yield true and so will the string "shu." without any int after the period

Related

How do greedy / lazy (non-greedy) / possessive quantifiers work internally?

I noticed that there are 3 different classes of quantifiers: greedy, lazy (i.e. non-greedy) and possessive.
I know that, loosely speaking, greedy quantifiers try to get the longest match by first reading in the entire input string and then truncate the characters one by one if the attempts keep failing; lazy quantifiers try to get the shortest match by first reading in the empty string and then add in the characters one by one if the attempts keep failing; possessive quantifiers try the same way as greedy quantifiers while they will stop matching if the first attempt fails.
However, I'm not sure how exactly the aboves are being implemented 'internally', and would like to ask for clarification (hopefully with examples).
For example, say we have the input string as "fooaaafoooobbbfoo".
If the regex is "foo.*" (greedy), will the foo in the regex first match the foo in the input string, and then .* reads in aaafoooobbbfoo as 'the entire string'? Or will .* first read in fooaaafoooobbbfoo as 'the entire string', and then truncates fooaaafoooobbbfoo to try matching the foo in the regex? If it is the latter, will fooaaafoooobbbfoo be truncated from its left or from its right in each attempt?
Will the answers to the above questions change if I replace "foo.*" with ".*foo" or "foo.*foo" as my regex? What about if I change those greedy quantifiers to lazy ones and possessive ones?
And if there are more than one quantifiers in a regex, how will the engine deal with the priority (if that matters)?
Thanks in advance!
For your input string fooaaafoooobbbfoo.
Case 1: When you're using this regex:
foo.*
First remember this fact that engine traverses from left to right.
With that in mind above regex will match first foo which is at the start of input and then .* will greedily match longest possible match which is rest of the text after foo till end. At this point matching stops as there is nothing to match after .* in your pattern.
Case 2: When you're using this regex:
.*foo
Here again .* will greedily match longest possible match before matching last foo which is right the end of input.
Case 3: When you're using this regex:
foo.*foo
Which will match first foo found in input i.e. foo at the start then .* will greedily match longest possible match before matching last foo which is right the end of input.
Case 4: When you're using this regex with lazy quantifier:
foo.*?foo
Which will match first foo found in input i.e. foo at the start then .*? will lazily match shortest possible match before matching next foo which is second instance of foo starting at position 6 in input.
Case 5: When you're using this regex with possessive quantifier:
foo.*+foo
Which will match first foo found in input i.e. foo at the start then .*+ is using possessive quantifier which means match as many times as possible, without giving back. This will match greedily longest possible match till end and since possessive quantifier doesn't allow engine to backtrack hence presence of foo at the end of part will cause failure as engine will fail to match last foo.

Difference (if any) between .+? and .*

I am looking through some old code bases and have come across two regular expression parts that I think are semantically identical. Wondering it the Stackoverflow community can confirm my understanding.
RegEx 1: (.+?) - One or more characters, but optional
RegEx 2: (.*) - Zero or more characters
I keep thinking of different scenarios but can't think of any input where both expressions wouldn't be the same.
(.+?) means match one or more character, but instead of the default greedy matching (match as much as possible), the ? after the quantifier makes the matching lazy (match as few as possible).
Conceptually, greedy matching will first try the longest possible sequence that can be formed by the pattern inside, then gradually reduce the length of the sequence as the engine backtracks. Lazy matching will first try the shortest possible sequence that can be formed by the pattern inside, then gradually increase the length of the sequence as the engine backtracks.
Therefore, (.+?) and (.*) are completely different. Given a string "abc", the pattern (.+?) will match "a" for the first match, while (.*) will match "abc" for the first match.
When you correct the pattern to the intended meaning: ((?:.+)?), it is exactly the same as (.*) in behavior. Since quantifier is greedy by default, ((?:.+)?) will first try the case of .+ before attempting the case of empty string. And .+ will try the longest sequence before the 1 character sequence. Therefore, the effect of ((?:.+)?) is exactly the same as (.*): it will find the longest sequence and backtrack gradually to the case of empty string.
First,
. is any character
Next
* is zero or more
+ is one or more
? is one or zero
You're thinking that .+? is one or more of any character and 0 or 1 of them I'm guessing?
You're missing this:
Lazy modifier
*? is zero or more getting as few as possible
+? is one or more getting as few as possible
See here for further discussion
Greedy vs. Reluctant vs. Possessive Quantifiers

Regular Expressions: how to interpret *?

I know what * is and what ? is.
However, I don't understand what *? is. I know it's used to make the "greedy" * operator a lazy one, but still, how does that read if * is zero or more times and ? is one or one time.
Thank you.
EDIT:
I underline the fact that I know what *, ?, greedy and lazy are.
This is a trick that has been used to extend regexp syntax without adding more special characters. Of course saying "zero or one" after "zero or more" has no meaning... so the combination *? should be read as a single token meaning "zero or more - not greedy". In a similar way +? should be read as a single token meaning "one or more - not greedy".
Greedyness never changes what strings are matched and what are not matched, but it may change what is the match found. For example group 1 of (AB*?)B+ matches A in ABBBBB, but group 1 of (AB*)B+ matches ABBBB in the same string.
The question mark in "strange places" has been used also in other special combinations that are available in several regexp engines, for example:
(?=...) zero-width positive lookahead assertion
(?!...) zero-width negative lookahead assertion
(?:...) non-tagging group
as you see they all start with (? where clearly the question mark couldn't mean "zero or one" (we're at the beginning of an expression, zero or one of what?).
Read this - Watch Out for The Greediness!
In your example, when the ? is used after the *, it is making the * lazy, so if you use the example in the above link:
This greedy regex - <.*>
given this string
"This is a <EM>first</EM> test"
would match
<EM>first</EM>
(It was greedy - it took the biggest (widest) match it could)
This lazy regex - <.*?>
given this string
"This is a <EM>first</EM> test"
would match
<EM>
(It was lazy - it took the smallest (most narrow) match it could)
Consider the string AAABAAAAAAAAB matching with /.*B/ versus /.*?B/. The first finds the whole string (greedy) and the second stops with as few A's as possible.
(In a Perl or Java or PHP etc extraction this would matter; if you're just searching in vi, it stops at the first A either way.)
? by itself is match 0 or 1 times. But that's different from the *? usage.
(This is, basically, Perl-style regex. Some regexes might behave differently, but mostly like this.)
Here's a little Perl demo:
$a = "AAAAAAAAAAABAAAAAAB";
print " first: ";
print $1 if($a =~ /(.*B)/);
print "\nsecond: ";
print $1 if($a =~ /(.*?B)/);
print "\n";
* is zero or more times and ? is zero or one times, but *? is zero or more times, not greedily. It's its own entity.
* means "match the expression before this * any amount of times (including zero)"
? means "match the expression before this ? zero or one time"
Greedy vs. lazy means that the expression prefers to stop as soon as possible with matching, instead of getting the longest match as possible.
Whether or not *? means *, but then lazy, depends on your regex engine.

What does this regex pattern describe: ".{5,}+"

One of the HTML input fields in an app I'm working on is being validated with the following regex pattern:
.{5,}+
What is this checking for?
Other fields are being checked with this pattern which I also don't understand:
.+
We can break your pattern down into three parts:
The dot is a wildcard, it matches any character (except for newlines, by default, unless the /s modifier is set).
{5,} is specifies repetition on the dot. It says that the dot must match at least 5 times. If there was a number after the comma, the dot would have to match between 5 and that number of times, but since there's no number, it can match infinite times.
In your first pattern, the + is a possessive quantifier (see below for how + can mean different things in different situations). It tells the regular expression engine that once it's satisfied the previous condition (ie. .{5,}), it should not try to backtrack.
Your second pattern is simpler. The dot still means the same thing as above (works as a wildcard). However, here the + has a different meaning, and is a repetition operator, meaning that the dot must match 1 or more times (that could also be expressed as .{1,}, as we saw above).
As you can see, + has a different meaning depending on context. When used on its own, it is a repetition operator. However when it follows a different repetition operator (either *, ?, + or {...}) it becomes a possessive quantifier.
The + means after another quantifier ({5,}) means a possessive match, i.e. once a match is found, *do not backtrack**.
For instance, the pattern .{5,}x will match abcdex:
.{5,} matches abcdex.
x matches nothing.
So backtrack .{5,} and let it match abcde.
Now x matches that last x.
But .{5,}+x will not match abcdex:
.{5,}+ matches abcdex.
x matches nothing.
Cannot backtrack the .{5,}+. We have to stop here.
*: Even the pattern cannot be backtracked, the matched strings can still be deleted as a whole. For instance, a?.{5,}x will match {a? → a, .{5,}+ → bcdex, x → no match}, and then delete the whole .{5,}+ and a and restart with {a? → , .{5,}+ → abcdex, x → no match}. Therefore, we can also say that the + makes the quantifier "atomic".
On the other hand, + alone just mean {1,}, i.e. match one or more times.
Any character, 5 or more times.
"." means any character except a line break.
{m, n} defines a bounded interval. "m" is the min. "n" is the max. If n is not defined, as is here, it is unlimited.
"+" means possessive.
.{5,}+ means
Match any single character that is not a line break character
Between 5 and unlimited times; as many times as possible, without giving back (possessive)
.+ is the same thing but it matches between 1 and unlimited times, giving back as needed (greedy).
As I've mentioned many times before, I'm a huge fan of RegexBuddy. It's "Create" mode is excellent for deconstruction regular expressions.

What is the difference between .*? and .* regular expressions?

I'm trying to split up a string into two parts using regex. The string is formatted as follows:
text to extract<number>
I've been using (.*?)< and <(.*?)> which work fine but after reading into regex a little, I've just started to wonder why I need the ? in the expressions. I've only done it like that after finding them through this site so I'm not exactly sure what the difference is.
On greedy vs non-greedy
Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.
The ? as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.
References
regular-expressions.info/Repetition - Laziness instead of Greediness
Example 1: From A to Z
Let's compare these two patterns: A.*Z and A.*?Z.
Given the following input:
eeeAiiZuuuuAoooZeeee
The patterns yield the following matches:
A.*Z yields 1 match: AiiZuuuuAoooZ (see on rubular.com)
A.*?Z yields 2 matches: AiiZ and AoooZ (see on rubular.com)
Let's first focus on what A.*Z does. When it matched the first A, the .*, being greedy, first tries to match as many . as possible.
eeeAiiZuuuuAoooZeeee
\_______________/
A.* matched, Z can't match
Since the Z doesn't match, the engine backtracks, and .* must then match one fewer .:
eeeAiiZuuuuAoooZeeee
\______________/
A.* matched, Z still can't match
This happens a few more times, until finally we come to this:
eeeAiiZuuuuAoooZeeee
\__________/
A.* matched, Z can now match
Now Z can match, so the overall pattern matches:
eeeAiiZuuuuAoooZeeee
\___________/
A.*Z matched
By contrast, the reluctant repetition in A.*?Z first matches as few . as possible, and then taking more . as necessary. This explains why it finds two matches in the input.
Here's a visual representation of what the two patterns matched:
eeeAiiZuuuuAoooZeeee
\__/r \___/r r = reluctant
\____g____/ g = greedy
Example: An alternative
In many applications, the two matches in the above input is what is desired, thus a reluctant .*? is used instead of the greedy .* to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.
The pattern A[^Z]*Z also finds the same two matches as the A.*?Z pattern for the above input (as seen on ideone.com). [^Z] is what is called a negated character class: it matches anything but Z.
The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.
References
regular-expressions.info/Repetition - An Alternative to Laziness, Negated Character Classes and Possessive Quantifiers
Example 2: From A to ZZ
This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.
eeAiiZooAuuZZeeeZZfff
These are the matches for the above input:
A[^Z]*ZZ yields 1 match: AuuZZ (as seen on ideone.com)
A.*?ZZ yields 1 match: AiiZooAuuZZ (as seen on ideone.com)
A.*ZZ yields 1 match: AiiZooAuuZZeeeZZ (as seen on ideone.com)
Here's a visual representation of what they matched:
___n
/ \ n = negated character class
eeAiiZooAuuZZeeeZZfff r = reluctant
\_________/r / g = greedy
\____________/g
Related topics
These are links to questions and answers on stackoverflow that cover some topics that may be of interest.
One greedy repetition can outgreed another
Regex not being greedy enough
Regular expression: who's greedier
It is the difference between greedy and non-greedy quantifiers.
Consider the input 101000000000100.
Using 1.*1, * is greedy - it will match all the way to the end, and then backtrack until it can match 1, leaving you with 1010000000001.
.*? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1, eventually matching 101.
All quantifiers have a non-greedy mode: .*?, .+?, .{2,6}?, and even .??.
In your case, a similar pattern could be <([^>]*)> - matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than > in-between < and >).
See Quantifier Cheat Sheet.
Let's say you have:
<a></a>
<(.*)> would match a></a where as <(.*?)> would match a.
The latter stops after the first match of >. It checks for one
or 0 matches of .* followed by the next expression.
The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.