首页 > 解决方案 > python:使用正则表达式查找特定单词

问题描述

这是我的字符串:

您在 xxxx 银行 'debit/credit/deposit/....' 卡上的 inr '1897.00' 的 'xxxx' 交易的一次性密码以 '0000' 结尾是 0000"

xxxx- 字符串,0000- 数字

我想用单引号(')获取所有值

这是我尝试过的:

[a-z ]+, ([a-z]+)[a-z ]+([0-9\.]+)到这里为止是正确的

现在我想获取(借方/贷方/...),我正在做:

在你的[a-z]+银行[a-z]+[a-z ]+([0-9]+)[a-z ]+[0-9]

更好的方法应该是什么?

标签: pythonregex

解决方案


您正在寻找的正则表达式很简单r"'(.*?)'"。下面的示例程序:

import re

regex = r"'(.*?)'"

test_str = "\"one time password for your transaction at, 'xxxx' of inr '1897.00' on your xxxx bank 'debit/credit/deposit/....' card ending '0000' is 0000\""

matches = re.finditer(regex, test_str)

for matchNum, match in enumerate(matches):
    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

哪个输出:

Match 0 was found at 44-50: 'xxxx'
Match 1 was found at 58-67: '1897.00'
Match 2 was found at 86-113: 'debit/credit/deposit/....'
Match 3 was found at 126-132: '0000'

在此处了解有关使用正则表达式的更多信息:https ://regex101.com/


推荐阅读