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. What could be the most effective approach for this?
Expected result - ["app", "agency"]
We can use match()
, twice :
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')
-> Here only data after NOT
is needed so we can use, query.split('NOT')[1]
Step 2 : Use regex rx.exec(res)[1]
to get the value in between the paranthesis.
Step 3 : Get the values before and after 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.