SoFunction
Updated on 2025-03-04

Use regular to press the last "_"segment" character

Greed and laziness
When a regular expression contains quantifiers that can accept duplicates (specified number of codes, such as *, {5, 12}, etc.), the usual behavior is to match as many characters as possible. Consider this expression: a.*b, which will match the longest string starting with a and ending with b. If you use it to search for aabab, it will match the entire string aabab. This is called greed matching.

Sometimes, we need more lazy matching, that is, matching as few characters as possible. The quantifiers given above can be converted into lazy matching patterns, just add a question mark after it. This way.*? means matching any number of repetitions, but using the least repetitions while making the entire match successful. Now take a look at the lazy version example:

a.*?b matches the shortest string that starts with a and ends with b. If you apply it to aabab, it will match aab and ab.

Table 5. Lazy quantifier *? Repeat any time, but repeat as few as possible.
+? Repeat 1 or more times, but repeat as few as possible
?? Repeat 0 or 1 time, but repeat as little as possible
{n,m}? Repeat n to m times, but repeat as few as possible.
{n,}? Repeat more than n times, but repeat as few as possible.
Another method.