Skip to main content
 首页 » 编程设计

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

2024年08月21日39zhengyun_ustc

来自这个字符串

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']