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.

user232343
  • 2,008
  • 5
  • 22
  • 34

2 Answers2

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

Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
  • 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 :/. – user232343 Mar 24 '14 at 01:47
  • 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. – aliteralmind Mar 24 '14 at 01:53
  • Yes, I need to capture :var and :var2 (and others if exist with pattern like /:something). I will update my question. – user232343 Mar 24 '14 at 01:55
  • 1
    I'm not sure if it's possible to have a [variable number of capture groups](http://stackoverflow.com/questions/5018487/regular-expression-with-variable-number-of-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? – Michael Tang Mar 24 '14 at 02:10
  • Okay, thank you @MichaelTang. I didn't catch that part of his comment-response until you mentioned it. Updated my answer. – aliteralmind Mar 24 '14 at 02:24
1

Here is how you can match both of them:

www.test.com/something/:var/else/:var2'.match(/\:(\w+)/g)
[":var", ":var2"]
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
uroslates
  • 479
  • 4
  • 2