Home > Enterprise >  Using regex capturing groups to dynamicaly return the group that matches the criteria
Using regex capturing groups to dynamicaly return the group that matches the criteria

Time:10-02

I have URL string such as /questions/12314454/syntax-error. I use 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 wont 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 catching groups to automatically return the group which matches a given criteria such as a number in this case, so i can replace it accordingly?

CodePudding user response:

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] ).*$
  • Related