Escape Sequences in Perl: Learn Perl By Doing It, Part 10

There are various escape sequences that you can use in most Perl-like regular expression languages (including Java) that allow you to match certain types of characters, such as numbers, spaces or alphanumeric strings. We'll look at the most common and useful varieties in this tutorial.



 
use strict;
use warnings;

$|=1;

sub main {
    
    # d digit
    # s space
    # S non-space
    # w alphanumeric
    
    # Some examples; in the following examples,
    # each example shows the text, the regular expression
    # and the output, in that order.
    
    # Digits:
    # 'I am 117 years old tomorrow.'
    # (d+)
    # Matched: '117'
    
    # Space (will also match a tab)
    # I am 117 years old tomorrow.
    # (ams*d+)
    # Matched: 'am 117'
    
    # S (non space -- note, capital 'S')
    # 'I am 117 years old tomorrow.'
    # (yS+)
    # Matched: 'years'
    
    # Alphanumeric, including underscore
    # w
    # 'Iam117yearsold_tomorrow.'
    # (w*)
    # Matched: 'yearsold_tomorrow'
    
    my $text = 'I am 117 years old tomorrow.';
    
    if($text =~ /(yS+)/) {
        print "Matched: '$1'n";
    }

    
    
}

main();