我已经搞了几个小时了,但似乎无法破解它。我基本上试图创建一个类似于 php 的 echo(不带参数)的 js 正则表达式。以下是我试图获取的模式和值。
var reg = /echo +[^\s(].+[//"';]/;
'echo "test";'.match(reg); //echo "test";
'echo test'.match(reg); //echo test
'echo "test me out"; dd'.match(reg); //echo "test me out"
'echo "test me out" dd'.match(reg); //echo "test me out"
'echo test;'.match(reg); //echo test;
'echo "test "'.match(reg); //echo "test "
"echo 'test'".match(reg); //echo 'test'
//These should all return null
'echo (test)'.match(reg);
'/echo test'.match(reg);
'"echo test"'.match(reg);
"'echo test'".match(reg);
我在这里做了一个例子: http://jsfiddle.net/4HS63/
最佳答案
您似乎正在寻找
var reg = /^echo +(?:\w+|"[^"]*"|'[^']*');?/;
^ // anchor for string beginning
echo // the literal "echo"
+ // one or more blanks
(?: // a non-capturing group around the alternation
\w+ // one or more word characters ( == [a-zA-Z0-9_])
| // or
"[^"]*" // a quote followed by non-quotes followed by a quote
|'[^']*' // the same for apostrophes
)
;? // an optional semicolon
关于JavaScript Regexp 来模拟 echo 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18021259/