I am writing a search bar with an autocomplete feature that is hooked up to an endpoint. I am using regex to determine the "context" that I am in inside of the query I type in the search bar. The three contexts are "attribute," "value," and "operator." The two operators that are allowed are "AND" and "OR." Below is an example of an example query.
Color: Blue AND Size: "Women's Large" (<-- multi-word values or attribute names are surrounded by quotation marks)
I need my regex to match after you put a space after Blue, and if the user begins type "A/AN/AND/O/OR", I need it to match. Once they have put a space after the operator, I need it to stop matching.
This is the expression I have come up with.
const contextIsOperator = /[\w\d\s"]+: *[\w\s\d"]+ [\w]*$/
It matches once I put a space after "Blue," but matches for everything I put after that. If I replace the last *
in the expression with a +, it works when I put a space after "Blue" and start manually typing one of the operators, but not if I just have a space after "Blue."
The pattern I have in my head written in words is:
- group of one or more characters/digits/spaces/quotation marks
- followed by a colon
- followed by an optional space
- followed by another group of one or more characters/digits/space/quotation marks
- followed by a space (after the value)
- followed by one or more characters (this is the operator)
How do I solve this problem?