Home > Net >  Create a regex to find queries separated by a semicolon or a space, similar to how GitHub Search wor
Create a regex to find queries separated by a semicolon or a space, similar to how GitHub Search wor

Time:06-28

I'm attempting to create a regex to catch the values of qualifier: value pairs, similar to how it's done in GitHub Search

As an example:

project name: foo/bar, foo/bar; status: online, offline; user: test location: Spain, Italy

A semicolon or space can be used to separate each qualifier:value pair.

Furthermore, each value can have multiple parameters separated by commas:

status: online, offline

The goal is to capture the specific qualifier's concrete value.

My current solution is as follows:

function getMatch(qualifier, string) {
    var formattedStr = string.replace(/ \/ | \/|\/ /g, "/");

    const regex = new RegExp(`${qualifier}:[\\s]?([,/A-Za-z0-9_-]*)[;\\s]?`, "g");
    var match = (formattedStr.match(regex) || []).map((e) =>
        e.replace(regex, "$1")
    );
    console.log(match)
}

However, if the value contains multiple parameters separated by commas, it will only catch the first occurrence:

For status: online, offline it will catch the value online only.

CodePudding user response:

You're missing a space character in your character class here: [,/A-Za-z0-9_-]

Also, you can make your life a bit better by using a letter wildcard \w instead of the A-Za-z0-9 bit.

Here's my tweaked version: https://regexr.com/6ok61

  • Related