我正在为 Python 的 re
而苦苦挣扎。我不知道如何以干净的方式解决以下问题。
我想提取 URL 的一部分,
到目前为止我尝试了什么:
url = http://www.example.com/this-2-me-4/123456-subj
m = re.search('/[0-9]+-', url)
m = m.group(0).rstrip('-')
m = m.lstrip('/')
这给我留下了所需的输出 123456
,但我觉得这不是提取 slug 的正确方法。
我怎样才能更快更干净地解决这个问题?
最佳答案
通过在要捕获 (...)
的正则表达式部分周围放置括号来使用捕获组。您可以通过将其编号作为参数传递给 m.group()
来获取捕获组的内容:
>>> m = re.search('/([0-9]+)-', url)
>>> m.group(1)
123456
来自 the docs :
(...)
Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the\number
special sequence, described below. To match the literals'('
or')'
, use\(
or\)
, or enclose them inside a character class:[(] [)]
.
关于python - 如何在 Python 中使用正则表达式从 URL 中提取 slug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24016988/