问题描述
我有一个 URL,我正在尝试将它与正则表达式匹配以拉出一些组.我遇到的问题是 URL 可以以 或 结尾,以/"和更多 URL 文本结尾.我想匹配这样的网址:
I have a URL, and I'm trying to match it to a regular expression to pull out some groups. The problem I'm having is that the URL can either end or continue with a "/" and more URL text. I'd like to match URLs like this:
但不匹配这样的东西:
所以,我认为我最好的选择是这样的:
So, I thought my best bet was something like this:
/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)[/$]
末尾的字符类包含/"或行尾.不过,字符类似乎对其中的$"不满意.我怎样才能最好地区分这些 URL,同时仍然拉回正确的组?
where the character class at the end contained either the "/" or the end-of-line. The character class doesn't seem to be happy with the "$" in there though. How can I best discriminate between these URLs while still pulling back the correct groups?
推荐答案
/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$
第一捕获组(.+)
.+
匹配任何字符(行终止符除外)
.+
matches any character (except for line terminators)
+
量词 - one 和 unlimited 次之间的匹配,尽可能多次,返回需要(贪婪)
+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
第二捕获组(\d{4}-\d{2}-\d{2})
\d{4}
匹配一个数字(等于 [0-9]
)
\d{4}
matches a digit (equal to [0-9]
)
{4}
量词 — 完全匹配4次
{4}
Quantifier — Matches exactly 4 times
-
字面上匹配字符 -
(区分大小写)
\d{2}
匹配一个数字(等于 [0-9]
)
\d{2}
matches a digit (equal to [0-9]
)
{2}
量词 — 完全匹配 2 次
{2}
Quantifier — Matches exactly 2 times
-
字面上匹配字符 -
(区分大小写)
\d{2}
匹配一个数字(等于 [0-9]
)
\d{2}
matches a digit (equal to [0-9]
)
{2}
量词 — 完全匹配 2 次
{2}
Quantifier — Matches exactly 2 times
-
与字符 -
字面匹配 (区分大小写)
-
matches the character -
literally (case sensitive)
第三捕获组(\d+)
\d+
匹配一个数字(等于 [0-9]
)
\d+
matches a digit (equal to [0-9]
)
+
量词 - one 和 unlimited 次之间的匹配,尽可能多次,返回需要(贪婪)
+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
第四捕获组(.*)?
?
量词 - 在 0 和 1 之间匹配,尽可能多,返回需要(贪婪)
?
Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
.*
匹配任何字符(行终止符除外)
*
量词——在零和无限次之间匹配,尽可能多的次数,返回需要(贪婪)
*
Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$
断言字符串末尾的位置
$
asserts position at the end of the string
这篇关于正则表达式匹配 URL 行尾或“/";特点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!