1

I am trying to extract express route named parameters with regex.

So, for example:

www.test.com/something/:var/else/:var2

I am trying with this regex:

.*\/?([:]+\w+)+

but I am getting only last matched group.

Does anyone knows how to match both :var and :var2.

2 Answers 2

1

The first problem is that .* is greedy, and will therefore bypass all matches until the final one is found. This means that the first :var is bypassed.

However, as you are searching for a variable number of capture groups (with thanks to @MichaelTang), I recommend using two regexes in sequence. First, use

^(?:.*?\/?\:\w+)+$

to detect which lines contain colon-elements...

Regular expression visualization

Debuggex Demo

...and then search that line repeatedly for, simply

\/:(\w+)

This places the text post-colon into capture group one.

Regular expression visualization

Debuggex Demo

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you on your answer. But still if I run > var res = 'www.test.com/something/:var/else/:var2'.match(/.*?\/?([:]+\w+)+/); in node.js, I am getting only one group, not both :/.
It is not clear then, from your question, exactly what your goal is. Are you trying to capture :var and also :var2? And is the format of every line exactly the same? Meaning always two colon-elements? Never three or one? Some more realistic and more examples input and expected output would be most helpful, if you want better answers.
Yes, I need to capture :var and :var2 (and others if exist with pattern like /:something). I will update my question.
I'm not sure if it's possible to have a variable number of capture groups... Perhaps it might be best to just programmatically build your Regex string with new Regex(str) based on the number of : chars in your path?
Okay, thank you @MichaelTang. I didn't catch that part of his comment-response until you mentioned it. Updated my answer.
1

Here is how you can match both of them:

www.test.com/something/:var/else/:var2'.match(/\:(\w+)/g)
[":var", ":var2"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.