0

I have URL string such as /questions/12314454/syntax-error. I use the following regex with capturing groups in a nginx map to get a number and replace it with a static string i.e. ID.

"~(.*/)([0-9]{5,})(/.*)$" $1ID$3;

However, above only works when I know that the number would be appearing in the second path of URL or second capturing group and won't work for URL such as:

/questions/syntax-error/73914774/
/73914774/questions/syntax-error/ 
/73914774/questions/73914774/ 
etc.

My question is how if possible, I can use regex's capturing groups to automatically return the group which matches a given criteria such as a number in this case, so I can replace it accordingly?

halfer
  • 19,824
  • 17
  • 99
  • 186
Maven
  • 14,587
  • 42
  • 113
  • 174
  • What do you mean "it won't work"? How exactly "doesn't it work"? Do you only want to match when the digits are the 2nd part of the path? – Bohemian Oct 02 '22 at 00:02
  • @Bohemian queite the opposite currently i replace the 2nd part in all the cases. What i want is to actually know which part of the path (capturing group) does contain numbers, so i can replace only that – Maven Oct 02 '22 at 07:29
  • Which match do you expect here, as there are 2 numbers? `/73914774/questions/73914774/` – The fourth bird Oct 02 '22 at 10:52

1 Answers1

1

If you only want to use 1 of the capturing groups, then drop the others and only keep the one you want. So in this case:

^.*[^0-9]([0-9]+).*$
Artemio Ramirez
  • 1,116
  • 1
  • 10
  • 23
  • Ramire sorry didnt get you but what i understand from your example that for e.g.`^.*[^0-9]([0-9]{5,}+).*$` will return the group or the numbers greatan than 5 in length irrespective of where they appear in the path? – Maven Oct 02 '22 at 07:33
  • This is what the regex captures using your examples https://regex101.com/r/0BGLW3/1 – Artemio Ramirez Oct 02 '22 at 07:44
  • Ok but how do i retrieve the matched value? Doing `$1` returns nothing. Also this regex `^.*[^0-9]([0-9]+).*$` doesnt differentiae between different sections of url in between `/`. – Maven Oct 02 '22 at 20:25