Category Archives: regular expressions

Use the \N regex character class to get “not a newline”

Perl 5.12 introduced an experimental regex character class to stand in for every character except one, the newline. The \N character class is everything but the newline. In prior versions of Perl, this is the same thing as the . meta character. That is, it’s the same as long as someone doesn’t add the /s […]

Use a smart match to match several patterns at once

The smart match operator (Item 23. Make work easier with smart matching) reduces many common comparisons to a few keystrokes, keeping with Perl’s goal of making the common things easy. You can use the smart match operator to make even less common tasks, such as matching many regular expressions at the same time, just as […]

Let perl create your regex stringification

Perl 5.14 changes how regular expression objects stringify. This might not seem like a big deal at first, but it exposes a certain sort of bug that you may have never considered. It even broke several modules on CPAN. If you previously tested for hard-coded stringifications of patterns, Perl 5.14 is probably going to break […]

Use branch reset grouping to number captures in alternations

Perl’s regular expressions have a simple rule for capturing groups. It counts the order of left parentheses to assign capture variables. Not all capture groups must actually match parts of the string, and Perl doesn’t care if they do. Perl assigns capture groups inside an alternation consecutively, even though it knows that only one branch […]

Detect regular expression match variables in your code

In Item 33: “Watch out for match variables”, you found out that the match variable $`, $&, and $` come with a performance hit. With all of the module code that you might use, you might be using those variables even though you didn’t code with them yourself. There’s a module that can tell you […]

Use /gc and \G in matches to separate alternations in separate, smaller patterns

Perl keeps track of the last position in a string where it had a successful global match (using the /g flag). You can access this position with the pos operator. With Perl 5.10, you can use the /p switch to get the per-match variable ${^MATCH} instead of the performance-dampening $&:

Know the difference between regex and match operator flags

The match and substitution operators, as well as regex quoting with qr//, use flags to signal certain behavior of the match or interpretation of the pattern. The flags that change the interpretation of the pattern are listed in the documentation for qr// in perlop (and maybe in other places in earlier versions of the documentation): […]