if ($key =~ /^\s*(\S.*?)\s*$/o)
I am especially confused about the meaning of (\S.*?).Any one can explain it for me?Thanks.
This should help you understand
Regarding this specifically: (\S.*?)
(
begins your capture group (group 1)\S
is non whitespace character.
is any character; *?
is "zero or more times" (non-greedy))
ends your capture groupIn plain english, your entire regex says
Kind of a weird regex, imho.
The code:
$key =~ /^\s*(\S.*?)\s*$/o
will produce a string in $1
where all leading and trailing whitespace characters (as defined by \s
) are removed.
The intention of the code seems to be checking that the string does not consists only of whitespaces, and obtain a trimmed string at the same time. However, it is only true with the assumption that the string doesn't contain multiple lines, where the regex will fail to match. For example, " somestring\nsomestring \nmore string"
.
As a summary, the cases that the test rejects are:
\s
)/\S.*\n.*\S/s
1.1Is .
in Perl equivalent to [\n]
? Does it exclude anything else when s
modifier is not in effect?
As for the o
modifier at the end, it seems that it is an obsolete modifier in the later versions of Perl. The modifier prevents old version of Perl from recompiling the pattern unnecessarily, but the current usage is limited to several use cases. Check the perlop
documentation (search for /o
) for more information.
Apart of the strict meaning of this regex, (well documented by @naomik), the whole instruction:
if ($key =~ /^\s*(\S.*?)\s*$/o)
means:
If $key
matches the regex, the group $1
will contains the same as $key
without leading and trailing spaces.
The \o
modifier (now obsolete), avoids the recompilation of the regex. You should use qr/^\s*(\S.*?)\s*$/
instead :
my $re = qr/^\s*(\S.*?)\s*$/;
if ($key =~ $re)
A lot of info here:
http://perldoc.perl.org/perlre.html#Regular-Expressions
I also use this to check regexs before I use them - I find it very helpful (and it also gives a good explanation of what each step is doing):