正则表达式模式解析多个字符串

时间:2018-04-06 14:08:35

标签: javascript regex

需要根据相当复杂的查询过滤字符串集合,我将查询输入作为字符串

var query =ti,su,ab(((study OR trail OR research pre/2 challeng*) n/1 (design* AND method*)) (behavior* n/1 behaviour*) OR ((behavior* or behaviour*)n/1 (change* near/6 modification*)));

查询可以更改

从这个查询INPUT字符串我想收集重要的单词:

我期望的结果= study trail research challeng* n/1design* method* behavior* behaviour* behavior* behaviour* n/1change* modification*

我的结果= study trail research challeng* design* method*behavior* behaviour* behavior* behaviour*change* modification*

我的问题在这里有时我会将两个单词连接成一个例子method*behavior*behaviour*change*,这是错误的

DEMO:

  • 这是我的正则表达式:从查询中删除字词:( ti, ab, su, AND, OR, NEAR/n, P/n, pre/n n/n ),括号()和逗号,
  

/?[()] | \ b(AND | OR |(NEAR | n | PRE | P)/ \ d +)(\ s | $)| \ b(ti | ab | su |,)\ b ? / GI

var query = "ti,ab,su(((study OR trail OR research pre/2 challeng*) n/1 (design* AND method*)) (behavior* n/1 behaviour*) OR ((behavior* or behaviour*)n/1 (change* near/6 modification*)))";

var subst= "";
var str = query.replace(/ ?[()]|\b(AND|OR|(NEAR|n|PRE|P)\/\d+)(\s|$)|\b(ti|ab|su|,)\b ?/gi,subst);
console.log(str)
每个单词都需要用空格来表示。

我正在寻找你的建议。

感谢。

1 个答案:

答案 0 :(得分:0)

用空格替换匹配的东西,然后压缩空间。

var query = "ti,ab,su(((study OR trail OR research pre/2 challeng*) n/1 (design* AND method*)) (behavior* n/1 behaviour*) OR ((behavior* or behaviour*)n/1 (change* near/6 modification*)))";

var subst= " ";
var str = query.replace(/ ?[()]|\b(AND|OR|(NEAR|n|PRE|P)\/\d+)(\s|$)|\b(ti|ab|su|,)\b ?/gi,subst);
str = str.replace(/^ +|( ) +| +$/g,"$1");
console.log(str)