python - 正则表达式:跳过组中字符的第一个匹配项?

标签 python regex

来自这个字符串

s = 'stringalading-0.26.0-1'

我想提取部分 0.26.0-1。我可以想出各种方法来实现这一点,使用拆分或使用像这样的模式的正则表达式

pattern = r'\d+\.\d+\.\d+\-\d+'

我还尝试使用一组字符,如下所示:

pattern = r'[.\-\d]+'

这给了我:

In [30]: re.findall(pattern, s)
Out[30]: ['-0.26.0-1']

所以我想知道:是否可以跳过组中第一次出现的字符,在本例中是第一次出现的-

最佳答案

is it possible to to skip the first occurrence of a character in a group, in this case the first occurrence of -?

NO,因为在匹配的时候,正则引擎会从左到右处理字符串,一旦找到匹配的模式,匹配的文本 block 就会被写入匹配缓冲区。因此,要么编写一个仅匹配您需要的正则表达式,要么通过从左侧去除不需要的字符来对找到的结果进行后处理。

我认为您在这里不需要正则表达式。你可以split带有 - 的字符串并将 maxsplit 参数设置为 1,然后只访问第二项:

s = 'stringalading-0.26.0-1'
print(s.split("-", 1)[1])   # => '0.26.0-1'

参见 Python demo

此外,您的第一个正则表达式 works well :

import re
s = 'stringalading-0.26.0-1'
pat = r'\d+\.\d+\.\d+-\d+'
print(re.findall(pat, s)) # => ['0.26.0-1']

关于python - 正则表达式:跳过组中字符的第一个匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40233381/

相关文章:

regex - 在终端中使用 RegEx 从字符串中提取字符串

python - 动态过滤来自 sqlalchemy 的数据

python - 如何在列表的最后一个元素之前添加 "and"?

python - 从 C 执行 python 脚本

python - 如何告诉 Pandas read_csv 使用多个空格作为分隔符而不是单个空格?

Javascript Regex - 替换所有出现的匹配字符串,除了括号之间的任何字符串

python - Flask API 类型错误 : Object of type 'Response' is not JSON serializable

python - pandas read_csv 中的日期和时间

html - Postgresql——清理字符串中间的 HTML 标签

asp.net - 正则表达式在后台 url 标记中查找值