这符合你的第4行,并拒绝在过去4:
^(["'])(\\.|(?!\\|\1).)*\1$
一个快速的解释:
^ # the start of the input
(["']) # match a single- or double quote and store it in group 1
( # open group 2
\\. # a backslash followed by any char
| # OR
(?!\\|\1). # if no backslash or the quote matched in group 1 can be seen ahead, match any char
)* # close group 2 and repeat it zero or more times
\1 # the same quote as matched in group 1
$ # the end of the input
这里有一个小PHP演示:
<?php
$tests = array(
'"lol"',
"'was'",
'"\\"say\\""',
"'\\'what\\''",
'"m"y"',
"'ba'd'",
'"th\\\\"is"',
"'su\\\\'cks'"
);
foreach($tests as $test) {
if(preg_match('/^(["\'])(\\\\.|(?!\\\\|\1).)*\1$/', $test)) {
echo "valid : " . $test . "\n";
}
else {
echo "invalid : " . $test . "\n";
}
}
?>
产生:
valid : "lol"
valid : 'was'
valid : "\"say\""
valid : '\'what\''
invalid : "m"y"
invalid : 'ba'd'
invalid : "th\\"is"
invalid : 'su\\'cks'
如能在ideone可以看出:http://ideone.com/60mtE
这正是我一直在寻找。我误解了“(?!)”小组是如何工作的,并假定它只是拒绝了内容,而不是执行有条件的事情。谢谢! – connec 2011-02-08 22:10:36