Mike Gossland’s Perl Tutorial Course for Windows

Chapter 2: Matching and Substitution in Perl

IntroductionBinding Operator > Regular Expressions >
Examples > Substitution > Advanced Ideas

Examples of Regular Expressions

To try out what we learned in Regular Expressions it would be good to see a few pattern matches in practice to see how they go together.

Regular Expression  Meaning
/a.c/ the letter a followed by any character then c
/a+c/ one or more a's followed by c
/a*c/ zero or more a's followed by c, so even "c" matches.
/a?c/ zero or one a followed by c: "ac" or "c"
/a.+c/ a followed by one or more characters, then c
/a.*c/ a followed by zero or more characters, then c, so even "ac" matches.
/a|bc/ "a" or "bc"
/(a|b)c/ "ac" or "bc"
/(a|b)+c/ one or more a's or b's, followed by c:
ac, bc, aac, abc, aaac, abbabababbac.
/(a|A)\ssample\smatch/ "A" or "a" followed by one whitespace character, then "sample", then one whitespace character, then "match".
/\d\d\d-\d\d\d-\d\d\d\d/ Any phone number like this: 250-123-1234
/\(\d\d\d\)\s\d\d\d\-\d\d\d\d/ Any North American phone number like this: (250) 123-1234
/\(\d{3}\)\s\d{3}-\d{4}/ As above, but using the count specifier
/<title.*title>/ An html title tag, with any title. The .* match would include the > and <\ characters
/<title>.*<\/title>/ An html title tag, with any title. The </title> tag needs a backslash quote in front of the slash, \/, to prevent the slash from being taken as the end of the pattern The .* match would include only the title text, not the > and </ as above
/first.*second.*third/ Any sequence of text with the word first before the word second before the word third. Any or no characters can lie in between the words
/^\t+\S+\s*/ Any line of text starting with one or more tabs, containing at least one nonwhitespace characer, followed by no or some whitespace
/^b[aeiouy]+t/ Any line of text starting with b followed by any combination of 1 or more vowels and then the letter t/

If you are comfortable with these examples, continue on to learn how to perform substitutions.

Next Page

Search this site or the web:

just this site the whole web

Questions? Feedback?

Email me your comments!