nasserahmed009
nasserahmed009

Reputation: 146

Converting a query parameters string into a regex expression

I'm building an app with expressjs and mongoose, I'm trying to construct a search endpoint like the specified herein Spotify api https://developer.spotify.com/documentation/web-api/reference/search/search/

I have a problem figuring out how to convert the given query parameters into a regex to match the required results. my endpoint looks like this example.com/search?q=searchText

Requirements:

Upvotes: 1

Views: 229

Answers (1)

Chase
Chase

Reputation: 5615

Here are the regexes for each of your queries:-

NOTE: All regexes use global, multiline and case insensitive modifiers

  • q=roadhouse blues => ^.*?(?:roadhouse.*?blues|blues.*?roadhouse).*$ -> demo
  • q="roadhouse blues" => ^.*?(?:roadhouse blues).*$ -> demo
  • q=roadhouse NOT blues => ^(?!.*?blues).*?roadhouse.*$ -> demo
  • q=roadhouse OR blues => ^.*?(?:roadhouse|blues).*$ -> demo
  • q=bob year:2014 => ^.*?bob.*?in the year 2014.*$-> demo
  • q=bob year:2014-2020 => ^.*?bob.*?in the year (?:201[4-9]|2020).*$ -> demo

Most of these follow a very specific pattern and you should be able to convert queries into these regexes. The last 2 might require some finesse but you've to explain the specific use case of those 2 by examples.

Upvotes: 1

Related Questions