JavaScript Regexp 来模拟 echo 语句

标签 javascript regex

我已经搞了几个小时了,但似乎无法破解它。我基本上试图创建一个类似于 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/

相关文章:

javascript - 使用 javascript 定位 f.select Rails 表单助手

javascript - 从字符串中删除 <p> 标签的内容

c# - C# 中的正则表达式问题

php - 正则表达式的问题

javascript - 序列号的正则表达式

java - 使用@Pattern时显示属性文件消息?

javascript - 在 ready() 中访问 prop 属性?

javascript - 同时打开 mailto 并提交表单

php - 确认不起作用时替换上传的文档

javascript - 使用 jquery 从函数中排除子元素