首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python:使用regex查找特定单词

python:使用regex查找特定单词
EN

Stack Overflow用户
提问于 2018-04-24 15:30:47
回答 3查看 94关注 0票数 0

这是我的字符串:

在你的xxxx银行的“借方/信贷/存款/.”上,你的交易密码为“1897.00”的“xxxx”以“0000”结尾的卡片是“0000”

xxxx - string,0000 -数字

我想取单引号(‘)中的所有值。

,这就是我尝试过的:

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

现在我想取(借方/信用/.),我在做:

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

更好的方法应该是什么?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-04-25 04:17:44

做到这一点的最安全和最具表现力的方法是在两个单引号之间匹配不是单引号的任何内容(在这种情况下,贪婪或懒惰并不重要):

代码语言:javascript
复制
'[^']*'

演示

代码示例:

代码语言:javascript
复制
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()))
票数 0
EN

Stack Overflow用户

发布于 2018-04-24 15:47:44

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

代码语言:javascript
复制
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()))

其中产出:

代码语言:javascript
复制
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'

在这里了解有关使用regex的更多信息:https://regex101.com/

票数 0
EN

Stack Overflow用户

发布于 2018-04-24 15:47:44

如果你想要单引号中的所有字符,

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50005577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档