从字符串列表中提取薪资

10

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

有人能帮忙吗? 谢谢


你的模式可以匹配一个空字符串,所以实际上你是“请求”它的。你想匹配什么样的模式?带有空格作为数字分组符号的数字吗?尝试使用 r'(?<!\d)\d{1,3}(?: \d{3})*(?!\d)' - Wiktor Stribiżew
你可以尝试使用这个模式 (\d+(?: \d{1,3})?)€ 并使用 findall 方法来仅返回薪水。演示 - The fourth bird
np.concatenate(re.findall(regex,sal)[0],re.findall(regex,sal)[1]) - mohan111
你想提取仅跟随 的数字吗?尝试使用 r'(?<!\d)(\d{1,3}(?:[ \xA0]\d{3})*)\s*€'r'(?<!\d)(\d+|\d{1,3}(?:[ \xA0]\d{3})*)\s*€'。请参见 https://regex101.com/r/rwbpTx/1 - Wiktor Stribiżew
谢谢大家! - Ceal Clem
1个回答

10

使用 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']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接