2011-02-08 21 views
0

我试图制造一个正规表达式,将捕获一个有效的,任意字符串(如你可能键入它)从Ruby和PHP等语言,例如:正则表达式来检查典型的'字符串'(类型)语法

"lol"  // valid 
'was'  // valid 
"\"say\"" // valid 
'\'what\'' // valid 
"m"y"  // invalid 
'ba'd'  // invalid 
"th\\"is" // invalid 
'su\\'cks' // invalid 

我有点卡住试图匹配的内容转义引号正确而未能上双擒纵当时的报价。

任何帮助表示赞赏!

回答

4

这符合你的第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

+0

这正是我一直在寻找。我误解了“(?!)”小组是如何工作的,并假定它只是拒绝了内容,而不是执行有条件的事情。谢谢! – connec 2011-02-08 22:10:36

相关问题