Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Python, Lua and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Java, C, C++, Ruby, MySQL and Linux / Tomcat systems
Greedy v Global on regular expressions

Posted by admin (Graham Ellis), 15 January 2003
Here's a program I wrote today to illustrate default, greedy
and global regular expression matching.

Global By default, Perl will perform a single match.  If you add the g modifier and run the match in a list contest, it will return all non-overlapping matches.  If you add the g modifier and run the match in a scalar context, it will return the next match each time you run the match, and a false value when there are no more matches available.

Greedy. By default, the counts * + and ? (0 or more, 1 or more, 0 or 1) are greedy.  In other words, if there are two possible ways that they can match, they'll go for the longest match.  If you add an extra ? - so if you use *? +? or ??, they'll go for the shortest match instead.

In all cases, matching starts from the left so that the match you get back will be the leftmost one, except on the second and subsequent calls in a scalar context with the g modifier.

[localhost:~/jan03] graham% cat

$abcd = "<h1>This is a heading</h1>above <b>this</b> text";

@tag = ($abcd =~ /<(.*)>/);

print ("Whole string: $abcd\n");
print ("Greedy: ",join(" %% ",@tag),"\n");

@tag = ($abcd =~ /<(.*?)>/);
print ("Sparse: ",join(" %% ",@tag),"\n");

@tag = ($abcd =~ /<(.*?)>/g);
print ("Sparse and global: ",join(" %% ",@tag),"\n");
[localhost:~/jan03] graham% perl
Whole string: <h1>This is a heading</h1>above <b>this</b> text
Greedy: h1>This is a heading</h1>above <b>this</b
Sparse: h1
Sparse and global: h1 %% /h1 %% b %% /b
[localhost:~/jan03] graham%

This page is a thread posted to the opentalk forum at and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2018: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: • WEB: • SKYPE: wellho