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
 
20.9.2014 - We have just updated our course layouts and descriptions and added our 2015 schedule.

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.

Code:
[localhost:~/jan03] graham% cat greedyvglobal.pl


$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 greedyvglobal.pl
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 www.opentalk.org.uk 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., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho