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

Captain Obvious picture Captain Obvious · Jun 13, 2014 · Viewed 20.3k times · Source

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!

Answer

Sean Bright picture Sean Bright · Jun 13, 2014

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);