4

我正在寻找一个匹配以下 4 种情况的正则表达式(获取 id 以便我可以重写 url)

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/

当前的正则表达式如下,但在所有情况下它都不能正确获取 id。那里的任何专家都知道我做错了什么?

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

3 回答 3

3

.*(你第二次使用它)是贪婪的。因此,它会消耗所有内容,直到您的最后一个 ID。这就是为什么如果您有两个 ID,第一个 ID 会丢失。让它变得不贪婪:

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

如果您想为此添加更多参数,我还在?最后添加了一个。.*但是,无论如何,简单地拆分字符串/可能要简单得多。

于 2012-10-12T18:54:16.537 回答
1

I know it's not exactly what you were wanting, but have you considered something along the lines of:

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

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

于 2012-10-12T19:43:00.940 回答
1

.*通过将正则表达式中的第二个更改为.*?,您应该获得您期望的示例字符串的捕获组:

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

示例:http ://www.rubular.com/r/CdBgdA1PlY

于 2012-10-12T18:54:56.023 回答