如何将这个PHP正则表达式转换为Javascript正则表达式?

时间:2013-08-24 12:50:01

标签: php javascript regex

这是我的PHP正则表达式:

if(preg_match('/^(([^,]+,){4}[^,]+\n){3}$/', $all_questions))
{
    //Code here
}

这就是我尝试将其转换为Javascript的方式:

if(fullString.match('/^(([^,]+,){4}[^,]+\n){3}$/'))
{
    //Code here
}

虽然PHP和Javascript之间的正则表达式语言略有不同,但我不确定如何将它从PHP转换为Javascript。

以下是我要验证的示例:

question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4

我需要验证确切的格式,是:

string[comma]string[comma]string[comma]string[comma]string[linebreak]
string[comma]string[comma]string[comma]string[comma]string[linebreak]
string[comma]string[comma]string[comma]string[comma]string[linebreak]

每一行总是有5个字符串和4个逗号,永远不会更多而且永远不会少。

这就是我的PHP preg_match看起来的样子:

if(preg_match('/^(([^,]+,){4}[^,]+\n){3}$/', $fullString))
{
    //Code here
}

有人可以帮我把它转换为Javascript正则表达式吗?

非常感谢,谢谢!

1 个答案:

答案 0 :(得分:1)

您不需要在javascript中使用字符串。您只需使用正则表达式对象:

str.match(/^(([^,]+,){4}[^,]+\n){3}$/);

您可以亲自试用:http://jsfiddle.net/mBb4S/

此外,MDN在正则表达式上有一些不错的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

相关问题