我正在尝试从字符串列表中提取薪水。
我正在使用regex findall()函数,但它返回许多空字符串以及薪水,这在以后的代码中给我带来了问题。
sal= '41 000€ à 63 000€ / an' #this is a sample string for which i have errors
regex = ' ?([0-9]* ?[0-9]?[0-9]?[0-9]?)'#this is my regex
re.findall(regex,sal)[0]
#returns '41 000' as expected but:
re.findall(regex,sal)[1]
#returns: ''
#Desired result : '63 000'
#the whole list of matches is like this:
['41 000',
'',
'',
'',
'',
'',
'',
'63 000',
'',
'',
'',
'',
'',
'',
'',
'',
'']
# I would prefer ['41 000','63 000']
有人可以帮忙吗?
谢谢
最佳答案
当您在模式中使用捕获组时,使用re.findall将为您提供捕获组,并且您正在使用的组中几乎所有内容都是可选的,从而在结果中包含空字符串。
在您的模式中,您使用的[0-9]*
将匹配数字0+倍。如果对前导数字没有限制,则可以使用[0-9]+
使其不可选。
您可以将此模式与捕获组一起使用:
(?<!\S)([0-9]+(?: [0-9]{1,3})?)€(?!\S)
Regex demo | Python demo
说明
(?<!\S)
声明左侧的内容不是非空格字符(
捕获组[0-9]+(?: [0-9]{1,3})?
匹配1+位数字,后跟匹配空格和1-3位数字的可选部分)
关闭捕获组€
从字面上匹配(?!\S)
断言右侧的内容不是非空格字符您的代码可能如下所示:
import re
sal= '41 000€ à 63 000€ / an' #this is a sample string for which i have errors
regex = '(?<!\S)([0-9]+(?: [0-9]{1,3})?)€(?!\S)'
print(re.findall(regex,sal)) # ['41 000', '63 000']
关于python - 从字符串列表中提取薪水,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55513299/