python - 从字符串列表中提取薪水

标签 python regex string list findall

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

    相关文章:

    javascript - 正则表达式反向引用的结果正确吗?

    python - 如何在 Python 中将一个字符串 append 到另一个字符串?

    python - 当HTML代码不一致时,如何在python中使用bs4识别正确的td标签

    正则表达式排除前缀字符串?

    regex - 正则表达式匹配后未定义 Perl $1 变量

    c - 在 C 中使用 string.h 字符串对象时出错

    python - 如何为计算命令制作一个字符串?

    python - 在Python中,如何分割字符串并保留分隔符?

    python - Google App Engine 处理程序不显示内容

    python - 在 Tensorflow 中计算两组向量的余弦相似度