从字符串列表中提取工资

Cea*_*lem 10 python regex string list findall

我正在尝试从字符串列表中提取工资。我正在使用正则表达式 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']
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙吗?谢谢

The*_*ird 8

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

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

您可以将此模式与捕获组一起使用:

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

正则表达式演示| 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']
Run Code Online (Sandbox Code Playgroud)