尝试测试perl的位置函数和解析能力。我有一个正则表达式,我认为它是正确的,但是 perl 告诉我我有一个无与伦比的 [,但对我来说它看起来是转义的。
Unmatched [ in regex; marked by <-- HERE in m/\G.*[([ <-- HERE ^]+)]/ at perltest.pl line 5.
任何人都可以澄清为什么我从以下代码中收到该消息吗?
my $string = "one, [two] , [three], and [four].";
pos($string) = 0;
while (my $string =~ m{\G.*\[([^\]+)\]}cg)
{
my $value = $1;
print "Found value $value .\n";
};
最佳答案
否定的字符类没有终止。
你在哪里
[^\]+ # One or more characters that aren't «]», «+», ...
你应该有
[^\]]+ # One or more characters that aren't «]»
我什至会用
[^[\]]* # Zero or more characters that aren't «[» or «]»
关于regex - 不匹配 [ 在正则表达式中,尽管被转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28116770/