Tweet

How do I match brackets or other meta-characters in a regular expression?

You want to match (or replace) brackets (or other meta-characters) using a regular expression.

Brackets, backslashes, curly braces, and square braces are just a few of the meta-characters that mean something special in a perl regular expression. However, sometimes you want to be able to match them in a regular expression also.

Consider the following text:

    Bob Brown (47) saved 6 cats from a tree yesterday.

If you wanted to match Bob Brown's age (47), it would be easiest if you could say "get me the number within the brackets".

The solution

A backslash will escape any meta-character in a regular expression:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $text = "Bob Brown (47) saved 6 cats from a tree yesterday";

    $text =~ m/\((\d+)\)/;
    my $age = $1;

    print "Bob is $age years old\n";
    exit 0;

The produces the following output:

    Bob is 47 years old

You could also use the x modifier to space out your regular expression, and even to add comments to it:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $text = "Bob Brown (47) saved 6 cats from a tree yesterday";

    $text =~ m/
        \(  # A real bracket
        (   # Capture the output
        \d+ # One or more digits
        )   # Stop capturing
        \)  # The closing real bracket
        /x;
    my $age = $1;

    print "Bob is $age years old\n";

    exit 0;

See also

For more information on regular expressions, see:

    perldoc perlretut
    perldoc perlre
[Top]