Regular expression with optional groups

I am looking for one regex to match the following 4 cases (capturing an identifier so that I can rewrite the urls)

http://localhost/gallery/test-name/123456 http://localhost/gallery/test-name/123456/ http://localhost/gallery/test-name/123456/video-name/159 http://localhost/gallery/test-name/123456/video-name/159/ 

The current Regex is lower, but in all cases it does not capture identifiers. Do all experts know what I'm doing wrong?

 ^(.*)/gallery/(.*)/([0-9]{1,15})(/)?((.*)/([0-9]{1,15})(/)?)? 
+4
source share
3 answers

.* (your second use) is greedy. Therefore, it consumes everything until your last identifier. This is why the first identifier is lost if you have two of them. Instead, make it jagged:

 ^(.*)/gallery/(.*?)/([0-9]{1,15})(/)?((.*?)/([0-9]{1,15})(/)?)? 

I also added ? to the last .* if you want to add additional parameters to it. However, simply splitting the line / can be much simpler.

+3
source

Just changing the second .* In your regular expression to .*? , you should get the capture groups that you expect for your example line:

 ^(.*)/gallery/(.*?)/([0-9]{1,15})(/)?((.*)/([0-9]{1,15})(/)?)? 

Example: http://www.rubular.com/r/CdBgdA1PlY

+1
source

I know this is not exactly what you wanted, but did you consider something like:

 string l_url = "http://localhost/gallery/test-name/123456/video-name/159"; string l_id = l_url.Split( '/' )[5]; 

As you did not specify the language, the above is in C #, but can be easily converted to any other language.

+1
source

Source: https://habr.com/ru/post/1439457/


All Articles