这个正则表达式是什么意思?

4

可以有人告诉我它到底要匹配什么吗?

$exp = '/[\s]+col[\s]*=[\s]*"([^"]*)"/si';

1
它可以被压缩成 /\scol\s*=\s*"([^"]*)"/i - moinudin
1
这意味着有人对正则表达式的理解不是很好。 - tchrist
对于使用Windows平台的人来说,“RegexBuddy”应用程序非常有用,可以帮助理解和构建正则表达式模式。 - Scuzzy
@Scuzzy:我相信它也可以在Wine上运行。但无论如何,有许多免费的替代品:http://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world - mario
3个回答

3

如果你添加了/x修饰符,你可以使用注释编写正则表达式。因此,这里是一个冗长且有文档说明的版本(对于复杂的正则表达式总是建议这样做):

$exp = '/
          [\s]+     # one or more spaces
          col       #       col
          [\s]*     # zero or more spaces
          =         #        =
          [\s]*     # spaces
          "         #        "
          ([^"]*)   # anything but " and zero or more of it
          "         #        " 
    /six';

有时候你会看到 [^<">] 代替 [^"],这样的正则表达式能够更加容忍格式不正确的html。

可爱,正则表达式修饰符拼写为“六”。 - BoltClock
不错的多行语法...尽管有时你会在属性中找到<>,但大多数浏览器都能适应它。 - Abdullah Jibaly

3

看起来匹配的是 col="some value",对等号周围的空格非常宽容,不区分大小写,无论值是否为空。

顺便说一句,有趣的是s修饰符在这里有什么作用,因为没有.元字符。


@Abdullah Jibaly:是的,可能只是一个非常宽容的正则表达式。 - BoltClock
1
@Abdullah,以便它也与 COL="<value>" 匹配。 - moinudin
或许是因为 HTML 不区分大小写。 - mario
@mario:我也是这么想的。哪个元素有“col”属性?我知道textarea有“cols”(复数)... - BoltClock

1
我认为其他人已经给出了很好的答案。另外,如果这不是用于解析标记,则可以通过类似以下内容的字符串方面的功能来提高功能:
\s+ col \s* = \s* "( (?: \\. | [^\\"]+ )* )"
Perl'ish 会是:
use strict;
use warnings;

my $regex = qr/

    \s+ col \s* = \s* "( (?: \\. | [^\\"]+ )* )"

/sx;

my $string = q(
 col  =  " this'' is \" a test\s,
           of the emergency broadcast system,
           alright .\". cool."
);

if ( $string =~ /$regex/ )
{
     print "Passed  val =\n $1\n";

}
__END__

Passed  val =
  this'' is \" a test\s,
           of the emergency broadcast system,
           alright .\". cool.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接