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

瘦欲@ 提交于 2021-02-18 18:38:40

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/24209058/regex-to-match-strings-that-begin-with-specific-word-and-after-that-words-sepera

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!