小编典典

从字符串列表中提取薪水

python

我正在尝试从字符串列表中提取薪水。我正在使用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']

有人可以帮忙吗?谢谢


阅读 140

收藏
2021-01-16

共1个答案

小编典典

当在模式中使用捕获组时,使用re.findall将为您提供捕获组,并且您正在使用的组中几乎所有内容都是可选的,从而在结果中提供空字符串。

在您的模式中,您将使用[0-9]*匹配数字0+倍的数字。如果对前导数字没有限制,则可以改用[0-9]+使其为可选。

您可以将此模式用于捕获组:

(?<!\S)([0-9]+(?: [0-9]{1,3})?)€(?!\S)

正则表达式演示|
Python演示

说明

  • (?<!\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']
2021-01-16