您好,我偶然发现了一个与正则表达式相关但我无法解决的问题。
我需要对查询进行分词(将查询拆分为多个部分),假设以下面的示例为例:
These are the separate query elements "These are compound composite terms"
我最终需要的是一个包含 7 个标记的数组:
1) These
2) are
3) the
4) separate
5) query
6) elements
7) These are compound composite term
第七个标记由几个单词组成,因为它在双引号内。
我的问题是:是否可以使用一个正则表达式根据上述解释对输入字符串进行分词?
编辑
我对使用 Regex.exec
或类似代码而不是 split
来实现同样的事情的可能性感到好奇,所以我做了一些调查,然后是another question here .因此,作为问题的另一个答案,可以使用以下正则表达式:
(?:")(?:\w+\W*)+(?:")|\w+
具有以下单行使用场景:
var tokens = query.match(/(?:")(?:\w+\W*)+(?:")|\w+/g);
希望对你有用...
最佳答案
你可以使用这个正则表达式:
var s = 'These are the separate query elements "These are compound composite term"';
var arr = s.split(/(?=(?:(?:[^"]*"){2})*[^"]*$)\s+/g);
//=> ["These", "are", "the", "separate", "query", "elements", ""These are compound composite term""]
如果这些正则表达式在双引号之外,则此正则表达式将在空格处拆分,方法是使用先行确保空格后有偶数个引号。
关于javascript - 用于标记查询的 JavaScript 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328788/