I’m trying to implement a search input similar to Stackoverflow’s (in node.js/javascript).
- Parse tags delimited by brackets
- Parse keywords delimited by spaces
However, I don’t understand regex at all. I don’t even know if regexs are the way to go.
For example:
search field [search][search-query] [search-string]
// keywords: ['search', 'field']
// tags: ['search', 'search-query', 'search-string']
Unfortunately, I find it additionally difficult to search any help on this since searching for regex search tags returns HTML questions
Think you’ll need something like this:
You can apply it repeatedly (e.g. using the Javascript exec method) and then extract values from the first and second capturing groups to capture tags and keywords respectively.
To explain:
The outermost () brackets enclose a choice of matching either a tag (enclosed by square brackets []) or a keyword (not enclosed by square brackets). The ?: bit excludes this choice bit from a capturing group since we need to know specifically whether the matched expression is a tag or keyword and so need a separate capturing group for each.
The next bit [([^]]*)] matches a tag: the opening and closing square brackets need to be escaped with a backslash to make them literals. The bit within the square brackets is enclosed in normal brackets () to capture the text within in the first capturing group. The [^…] bit matches anything except what is listed after the caret – so in this case anything except the closing square bracket. This is repeated greedily using the *.
The | separates the choice and then we have the matching expression for a keyword: ([^\s]+). Again this is in brackets to make the results appear in a capturing group. This time we are matching anything except for whitespace one or more times.
Finally the /g is the global modifier so that all occurrences are matched.