python - 使用 Python 正则表达式从文本中提取信息

标签 python regex

我有一条短信:

text = 'dear customer your account xx9052 has been debited with inr25697.50 on 23-nov-18 info 
bil001582495861 icici bank the available balance is inr 363.25'

在这里,我试图从文本中提取帐号、金额、日期和可用余额等信息。

我用下面的正则表达式试过了:

pattern = 'your account (.*) has been debited with (.*) on (.*) info (.*) available balance is (.*\d)$'

if (re.search(pattern, text, re.IGNORECASE)):
    print(re.search(pattern, text, re.IGNORECASE).group(1)), \
    print(re.search(pattern, text, re.IGNORECASE).group(2)), \
    print(re.search(pattern, text, re.IGNORECASE).group(3)), \
    print(re.search(pattern, text, re.IGNORECASE).group(5))

我得到了想要的结果:

xx9333
inr 25697.50
23-nov-18
inr 363.25

但是当文本稍作修改时,我遇到了这个正则表达式模式的问题:

text = 'dear customer your account xx9052 has been debited with inr 25697.50 on 23-nov-18 info bil 001582495861 icici bank the available balance is inr 363.25 for dispute call 04033667777'

使用相同的正则表达式得到结果:

xx9333
inr 25697.50
23-nov-18
inr 363.25 for dispute call 04033667777

余额是用额外信息提取的,而它应该只是 inr 363.25.。我该如何解决这个问题,以便在两种情况下都使用单一模式正确提取信息?

最佳答案

我建议单独提取信息片段,而不是使用单一模式。

例如: 要获取金额,您可以使用正则表达式模式 - ([\d]+\.[\d]+) 它将从所需的字符串中获取十进制数字,您可以为帐号和日期等其他信息创建正则表达式。

更新:
如果您想使用相同的模板,请将您的正则表达式更改为

pattern = '您的帐户 (.*) 已在 (.*) 上用 (.*) 记帐,信息 (.*) 可用余额为 (.*[\d]+\.[\d] +)'

关于python - 使用 Python 正则表达式从文本中提取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59434140/

相关文章:

python - 如何使用已导入的变量?

python - 尝试写入文件时缺少变量

Python ctypes 函数指针

Python - 替换字符串中的非 ASCII 字符 (»)

javascript - 使用正则表达式从字符串中获取特殊字符前后的数字

python - 如何在python中对列表进行排序后获取原始索引

python - 使用 python 和 scikit-learn 的 DBSCAN : What exactly are the integer labes returned by make_blobs?

正则表达式前瞻、后瞻和原子组

javascript - If 语句中的正则表达式

java - Lambda 表达式函数式编程