python - 如何在 Python 中使用正则表达式从 URL 中提取 slug?

标签 python regex

我正在为 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/

相关文章:

python - 在 Docker 中编译 Julia 系统镜像

python - 有没有办法在不使用 Python 本地数据库的情况下获取 Chrome 历史记录和书签?

python - 如何在不覆盖当前内容的情况下写入文件?

python - 如何更改 tkinter 文本小部件中某些单词的颜色?

regex - 将 http 重定向到 https OS X Server 5.0.15

python - 如何正确交叉验证

Java 执行正则表达式

php - 使用多行字符串的正则表达式修剪行并缩小空格

regex - 如何使用单行解析需要多个匹配项的 csv 输出?

python - 使用带有\number 的组时出现 re.sub 问题