2

I have following perl pattern matching condition

(?:\s+\w+){2}

When it's applied on a Linux directory listing

-rw-rw-r-- 1 root root       36547 2011-03-18 18:41 abc.txt

It matches root root

What is ?: doing in this?

Borodin
  • 126,100
  • 9
  • 70
  • 144
user2896215
  • 507
  • 7
  • 20

1 Answers1

3

Brackets capture the string found in a regex. ?: will disable the capturing for the current bracket.

"1 root" is matched because the pattern matches two occurrences of one or more whitespace characters (\s) followed by one it more word characters (\w). See "Character Classes and other Special Escapes".

In the example given, the 1st word character that has a whitespace in front is "1", followed by some whitespace and again, one or more word characters.

For those who don't see it - try it out (you can remove the ?: to see the matching group $1, it will contain root):

my $str = '-rw-rw-r-- 1 root root     36574 2011-03-18 18:41 abc.txt';
if ( $str =~ m/(\s+\w+){2}/ ) {
    print "matches\n";
    print "\$1 contains " . (defined $1 ? $1 : "nothing it's undef") . "\n";
}else{
    print "does not match\n";
}
capfan
  • 817
  • 10
  • 26