@@ -5187,10 +5187,37 @@ SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
5187
5187
The quantifiers <literal>{1,1}</> and <literal>{1,1}?</>
5188
5188
can be used to force greediness or non-greediness, respectively,
5189
5189
on a subexpression or a whole RE.
5190
+ This is useful when you need the whole RE to have a greediness attribute
5191
+ different from what's deduced from its elements. As an example,
5192
+ suppose that we are trying to separate a string containing some digits
5193
+ into the digits and the parts before and after them. We might try to
5194
+ do that like this:
5195
+ <screen>
5196
+ SELECT regexp_matches('abc01234xyz', '(.*)(\d+)(.*)');
5197
+ <lineannotation>Result: </lineannotation><computeroutput>{abc0123,4,xyz}</computeroutput>
5198
+ </screen>
5199
+ That didn't work: the first <literal>.*</> is greedy so
5200
+ it <quote>eats</> as much as it can, leaving the <literal>\d+</> to
5201
+ match at the last possible place, the last digit. We might try to fix
5202
+ that by making it non-greedy:
5203
+ <screen>
5204
+ SELECT regexp_matches('abc01234xyz', '(.*?)(\d+)(.*)');
5205
+ <lineannotation>Result: </lineannotation><computeroutput>{abc,0,""}</computeroutput>
5206
+ </screen>
5207
+ That didn't work either, because now the RE as a whole is non-greedy
5208
+ and so it ends the overall match as soon as possible. We can get what
5209
+ we want by forcing the RE as a whole to be greedy:
5210
+ <screen>
5211
+ SELECT regexp_matches('abc01234xyz', '(?:(.*?)(\d+)(.*)){1,1}');
5212
+ <lineannotation>Result: </lineannotation><computeroutput>{abc,01234,xyz}</computeroutput>
5213
+ </screen>
5214
+ Controlling the RE's overall greediness separately from its components'
5215
+ greediness allows great flexibility in handling variable-length patterns.
5190
5216
</para>
5191
5217
5192
5218
<para>
5193
- Match lengths are measured in characters, not collating elements.
5219
+ When deciding what is a longer or shorter match,
5220
+ match lengths are measured in characters, not collating elements.
5194
5221
An empty string is considered longer than no match at all.
5195
5222
For example:
5196
5223
<literal>bb*</>
0 commit comments