Linux Blog

Perl Regular Expression Cheat Sheet

Filed under: Shell Script Sundays — Owen at 10:15 pm on Saturday, October 6, 2007

Regular Expressions can be tricky, that’s why it is a good idea to keep a quick “cheat sheet” handy when working with them, here’s a concise cheat sheet to get you started:

. Match any character
\a Match alarm
\d Match digit character
\D Match non-digit character
\e Match escape
\f Match form-feed
\n Match newline
\r Match return
\s Match whitespace character
\S Match non-whitespace character
\t Match tab
\w Match “word” character (alphanumeric and “_”)
\W Match non-word character
\022 Match octal char (i.e. 22 octal)
\xff Match hex char (i.e. ff in hex)

* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times

{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times

^ Match if at beginning
$ Match if at end

Examples:
\d{2}-\d{2}-\d{2} # match date in dd-mm-yy format
^[ \t]+ #match leading whitespace
[ \t]+$ #match trailing whitespace
^[ \t]+|[ \t]+$ #match leading or trailing whitespace

$string =~ m/text/; #returns true if $string contains text, case sensitive
$string =~ m/text$/i; #returns true if $string contains text
$string =~ s/text1/text/; #replace text1 with text2 in $string
$string !~ m/text/; #returns false if $string contains text, case sensitive
$string !~ m/text/i; #returns false if $string contains text

I find it useful to print it out and have it handy whenever I wade into the murky waters of regular expressions.

Related Posts


No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">