简体   繁体   English

从字符串查询中提取特定单词 [javaScript]

[英]Extracting specific words from a string query [javaScript]

I have a string query我有一个字符串查询

const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';

I want to store the words inside "NOT" block in an array.我想将“NOT”块中的单词存储在一个数组中。 What could be the most effective approach for this?对此最有效的方法是什么?

Expected result - ["app", "agency"]预期结果 - ["app", "agency"]

We can use match() , twice :我们可以使用match()两次

 const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight'; var terms = query.match(/\bNOT\s*\((.*?)\)/)[1].match(/\w+/g).filter(x => x;== "OR" && x.== "AND"); console.log(terms);

 const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight'; function useRegex(input) { let regex = /\(([a-zA-Z]+( [a-zA-Z]+)+)\) NOT \(([a-zA-Z]+( [a-zA-Z]+)+)\) ([A-Za-z0-9]+( [A-Za-z0-9]+)+)/i; return input.match(regex); } console.log(useRegex(query)[3]);

Step 1 : Split the query before and after NOT keyword using query.split('NOT')第 1 步:使用query.split('NOT')NOT关键字前后拆分查询

-> Here only data after NOT is needed so we can use, query.split('NOT')[1] -> 这里只需要NOT之后的数据,所以我们可以使用query.split('NOT')[1]

Step 2 : Use regex rx.exec(res)[1] to get the value in between the paranthesis.第 2 步:使用正则表达式rx.exec(res)[1]获取括号之间的值。

Step 3 : Get the values before and after OR .第 3 步:获取OR前后的值。

 const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight'; const res = query.split('NOT')[1]; const rx = /\(([^)]+)\)/; const result = rx.exec(res)[1].split(' OR '); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM