Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make ' ' mean \s* in Perl regular expressions?

Tags:

regex

perl

This would greatly improve the readability of many regular expressions I write, and when I write a single literal space in my regexes I almost always mean \s* anyway. So, is there a "mode" in Perl regular expressions that enables this, like /s to make . match newlines, etc.? A cursory read through perlre didn't give anything, but maybe I missed something or maybe there's a different way to achieve this?

Edit: What I mean is, currently I write qr/^\s*var\s+items\s*=\s*[\s*$/, and I'd instead like to write qr/^ var\s+items = [ $/ and have it mean the same thing using some means- and my question is whether such a means exists.

like image 212
Sundar R Avatar asked Dec 02 '25 04:12

Sundar R


2 Answers

Here's a sample of using an overload (http://perldoc.perl.org/perlre.html#Creating-Custom-RE-Engines) for your specific substitution.

myre.pm

package myre;
use overload;

sub import {
    overload::constant 'qr' => \&spacer;
}

sub spacer {
     my $re = shift;
     $re =~ s/ /qr{\s*}/ge;
     return $re;
}
1;

example.pl

use myre;
print "ok" if "this is\n\n a   test" =~ /this is a test/;
like image 159
clockwatcher Avatar answered Dec 04 '25 23:12

clockwatcher


Nope, there is no such functionality available. But there is the /x mode that prevents literal space from matching anything at all, so that you can visually structure your regex.

qr/\A\s* var \s* items \s*=\s* \[ \s*\z/x

(except in character classes – [ ] matches a space again).

like image 32
amon Avatar answered Dec 04 '25 23:12

amon