【问题标题】:Why does this javascript regex literal not work?为什么这个 javascript 正则表达式文字不起作用?
【发布时间】:2014-02-04 21:18:26
【问题描述】:
function fuzzQuery(rawQuery)
{
    re = /(?=[\(\) ])|(?<=[\(\) ])/;    

    strSplit = rawQuery.split(re);

    alert(strSplit);
};

不起作用(没有对话框)。

我检查了http://rubular.com/ 的表达式,它按预期工作。

re = /e/ 

确实有效。

输入字符串是

hello:(world one two three)

预期结果是:

hello:,(,world, ,one, ,two, ,three, )

我查看了以下 SO 问题:

Javascript simple regexp doesn't work

Why this javascript regex doesn't work?

Javascript regex not working

Javascript RegEx Not Working

但我不会犯错误,比如将表达式创建为字符串,或者当它是字符串时不使用双反斜杠。

【问题讨论】:

标签: javascript regex regex-lookarounds


【解决方案1】:

您的正则表达式的主要问题是 不支持Lookbehind

re = /(?=[\(\) ])|(?<=[\(\) ])/
                   ^^^ A problem...

相反,您可以使用替代方法:

re       = /(?=[() ])|(?=[^\W])\b/;
strSplit = rawQuery.split(re);
console.log(strSplit);

// [ 'hello:', '(', 'world', ' ', 'one', ' ', 'two', ' ', 'three', ')' ]

【讨论】:

  • 跛脚。有什么建议吗?
  • @dwjohnston 我添加了一个可能的替代方案。
【解决方案2】:

你可以使用这样的东西:

re = /((?=\(\) ))|((?=[\(\) ]))./;    

    strSplit = rawQuery.split(re);

    console.log(strSplit);

【讨论】:

    猜你喜欢
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多