Reputation: 51
Let's say i have the following string :
KEYWORD_1 OR "KEYWORD COMPOSITE_2" NOT "KEYWORD COMPOSITE_3" NOT "KEYWORD_4" AND "KEYWORD_5" KEYWORD_6 KEYWORD_7 KEYWORD_8 -KEYWORD_9
The result (this is not JSON format, just a visual formatting to explain the output) i want to get with my regex(es) is to split the string to the following three arrays of keywords, each one is corresponding to a delimiter (AND, OR, NOT) and contains all the words that follows every occurrence of the delimiter. Think of it like the google search field syntaxt :) :
final_result = {
{
OR: [KEYWORD_COMPOSITE_2]
},
{
AND: [
KEYWORD_1,
KEYWORD_5,
KEYWORD_6,
KEYWORD_7,
KEYWORD_8
]
},
{
NOT: [
KEYWORD_COMPOSITE_3,
KEYWORD_4,
KEYWORD_9
]
}
}
I am trying to do this in javascript with one or more regex.
Any idea ? any help ? thank you
Upvotes: 1
Views: 130
Reputation: 214949
You cannot do that with regexes alone, some programming is still required:
function parse(input) {
var keywords = ['AND', 'OR', 'NOT'];
var result = {}, kw = 'AND';
input.replace(/"(.+?)"|(\w+)/g, function($0, $1, $2) {
if(keywords.indexOf($2) >= 0) {
kw = $2;
} else {
if(!(kw in result))
result[kw] = [];
result[kw].push($1 || $2);
}
});
return result;
}
Upvotes: 1