2

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"]

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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]);

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.