これはあなたの最初の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
@connec、よろしいですか? –