Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:使用正则表达式查找特定单词_Python_Regex - Fatal编程技术网

python:使用正则表达式查找特定单词

python:使用正则表达式查找特定单词,python,regex,Python,Regex,这是我的字符串: 您在xxxx银行“借记/贷记/存款/…”上的“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] 更好的方法是什么?您要查找的正则表达式只是r“(.*

这是我的字符串:

您在xxxx银行“借记/贷记/存款/…”上的“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]


更好的方法是什么?

您要查找的正则表达式只是
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'

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

如果希望单引号中的所有字符

import re
string = "'xxxx' of inr '1897.00' on your xxxx bank 'debit/credit/deposit/....' card ending '0000' is 0000"
all_matches = re.findall(r"\'.+?\'",string)
print all_matches

最安全、最有效的方法是匹配两个单引号之间不是单引号的任何内容(在这种情况下贪婪或懒惰无关紧要):

代码示例:

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 match in matches:
    print ("Match was found at {start}-{end}: {match}".format(start = match.start(), end = match.end(), match = match.group()))

?请使用代码缩进设置问题的格式
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 match in matches:
    print ("Match was found at {start}-{end}: {match}".format(start = match.start(), end = match.end(), match = match.group()))