Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for an autocomplete feature

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:

  1. group of one or more characters/digits/spaces/quotation marks
  2. followed by a colon
  3. followed by an optional space
  4. followed by another group of one or more characters/digits/space/quotation marks
  5. followed by a space (after the value)
  6. followed by one or more characters (this is the operator)

How do I solve this problem?

like image 455
Sean San Avatar asked Dec 07 '25 09:12

Sean San


1 Answers

Change [\w]* to something that just matches AND, OR, or one of their prefixes. Then you can make it optional with ?

[\w\s"]+: *[\w\s"]+ (A|AN|AND|O|OR)?$

DEMO

Note that Size: Women's Large won't match this because the apostrophe isn't in \w; that only matches letters, digits, and underscore. You'll need to add any other punctuation characters that you want to allow in these fields to the character set.

like image 76
Barmar Avatar answered Dec 09 '25 22:12

Barmar