如何在Python中匹配字符串或字符的开头

use*_*145 5 python regex findall

我有一个由参数号_参数号组成的字符串:

dir = 'a1.8000_b1.0000_cc1.3000_al0.209_be0.209_c1.344_e0.999'
Run Code Online (Sandbox Code Playgroud)

我需要在选择的参数后面得到数字,即

  • par='be' - >需要0.209
  • par='e' - >需要0.999

我试过了:

num1 = float(re.findall(par + '(\d+\.\d*)', dir)[0])
Run Code Online (Sandbox Code Playgroud)

但对于par='e'将匹配0.209 0.999,所以我试图用参数字符串或下划线的开头匹配在一起:

num1 = float(re.findall('[^_]'+par+'(\d+\.\d*)', dir)[0])
Run Code Online (Sandbox Code Playgroud)

由于某种原因不起作用.

有什么建议?谢谢!

Mar*_*ers 4

您的[^_]模式匹配除下划线之外的任何字符

使用 a(..|..) 分组代替:

float(re.findall('(?:^|_)' + par + r'(\d+\.\d*)', dir)[0])
Run Code Online (Sandbox Code Playgroud)

(?:..)在那里使用了一个非捕获组,这样它就不会干扰您原来的组索引。

演示:

>>> import re
>>> dir = 'a1.8000_b1.0000_cc1.3000_al0.209_be0.209_c1.344_e0.999'
>>> par = 'e'
>>> re.findall('(?:^|_)' + par + r'(\d+\.\d*)', dir)
['0.999']
>>> par = 'a'
>>> re.findall('(?:^|_)' + par + r'(\d+\.\d*)', dir)
['1.8000']
Run Code Online (Sandbox Code Playgroud)

详细来说,当使用字符组 ( [..]) 并以脱字符号 ( )开始^该组时,您会反转字符组,将其从匹配列出的字符转变为匹配其他所有字符

>>> re.findall('[a]', 'abcd')
['a']
>>> re.findall('[^a]', 'abcd')
['b', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)