Part of what makes Perl such a useful language is its powerful string-matching
and handling capabilities. Regular expressions are basically patterns a
programmer can compare a string of text to. Matching a regular expression with
a string of text either returns true or false. The two main pattern matching
operators are m// and s//. These are the matching and
substitution operators respectively. Another function that makes use of regular
expressions is split
The matching operator m// is normally written //.
Perl allows you to change the delimiters to something besides /. If you don't
change the delimiters from /, you can use // instead of m//.
Now for a quick example of m//:
Now for a quick example of s///:
This function goes through each of the items in @machine_os. If any of them contain Windows, the thing between the first set of //. It is replaced with Linux the string between the second and third /'s. You can see why you've gotta love Perl. Instead of 1 OpenBSD machine, 2 Windows machines and a Linux box, I now have 1 OpenBSD box and 3 Linux machines. At least that is what @machines_os now contains.
Now on to Quantifiers in regular expressions.
while(<>){ if(/the/){ #does $_ contain the print "Your line of text contains the word 'the'\n"; } }
Now for a quick example of s///:
@machines_os=("OpenBSD","Windows","Linux", "Windows"); foreach(@machines_os){ s/Windows/Linux/; }
This function goes through each of the items in @machine_os. If any of them contain Windows, the thing between the first set of //. It is replaced with Linux the string between the second and third /'s. You can see why you've gotta love Perl. Instead of 1 OpenBSD machine, 2 Windows machines and a Linux box, I now have 1 OpenBSD box and 3 Linux machines. At least that is what @machines_os now contains.
Now on to Quantifiers in regular expressions.
|
---|
Replies are listed 'Best First'. | |
---|---|
RE: String matching and Regular Expressions
by neophyte (Curate) on Nov 02, 2000 at 14:48 UTC | |
Pattern Matching:#2
by Anonymous Monk on Mar 23, 2000 at 01:29 UTC | |
by providencia (Pilgrim) on Apr 05, 2000 at 08:37 UTC | |
by little_mistress (Monk) on Apr 06, 2000 at 00:59 UTC | |
Re: String matching and Regular Expressions
by iza (Monk) on Mar 14, 2002 at 13:10 UTC | |
by rdfield (Priest) on Mar 14, 2002 at 13:18 UTC | |
Re: String matching and Regular Expressions
by lvanhout (Curate) on Jun 20, 2004 at 19:59 UTC | |
Re: String matching and Regular Expressions
by boxer (Initiate) on Apr 26, 2002 at 15:27 UTC | |
Re: String matching and Regular Expressions
by Perlin_the_Red (Initiate) on Sep 16, 2002 at 18:05 UTC | |
A reply falls below the community's threshold of quality. You may see it by logging in. |
Back to
Tutorials