Search code examples
regexprefixslash

Regex to match strings that begin with specific word and after that words seperated by slashes


So i want to match all strings of the form with a regex

(word1|word2|word3)/some/more/text/..unlimited parts.../more

so it starts with specific word and it does not end with /

examples to match:

word1/ok/ready
word2/hello
word3/ok/ok/ok/ready

What i want in the end is when i have a text with above 3 examples in it (spread around in a random text), that i receive an array with those 3 matches after doing regex.exec(text);

Anybody an idea how to start? Thanks!


Solution

  • Something like this should work:

    ^(word1|word2|word3)(/\w+)+$
    

    If you're using this in an environment where you need to delimit the regex with slashes, then you'll need to escape the inner slash:

    /^(word1|word2|word3)(\/\w+)+$/
    

    Edit

    If you don't want to capture the second part, make it a non-capturing group:

    /^(word1|word2|word3)(?:\/\w+)+$/
                          ^^ Add those two characters
    

    I think this is what you want, but who knows:

    var input = '';
    input += 'here is a potential match word1/ok/ready that is followed by another ';
    input += 'one word2/hello and finally the last one word3/ok/ok/ok/ready';
    
    var regex = /(word1|word2|word3)(\/\w+)+/g;
    var results = []
    
    while ((result = regex.exec(input)) !== null) {
        results.push(result[0].split('/'));
    }
    
    console.log(results);