Python正则表达式匹配引号之间的文本 [英] Python regex match text between quotes

查看:57
本文介绍了Python正则表达式匹配引号之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下脚本中,我想提取双引号 (") 之间的文本.但是,python 解释器并不满意,我不知道为什么...

In the following script I would like to pull out text between the double quotes ("). However, the python interpreter is not happy and I can't figure out why...

import re

text = 'Hello, "find.me-_/\\" please help with python regex'
pattern = r'"([A-Za-z0-9_\./\\-]*)"'
m = re.match(pattern, text)

print m.group()

输出应该是find.me-/\.

推荐答案

match 从文本的开头开始搜索.

match starts searching from the beginning of the text.

改用search:

#!/usr/bin/env python

import re

text = 'Hello, "find.me-_/\\" please help with python regex'
pattern = r'"([A-Za-z0-9_\./\\-]*)"'
m = re.search(pattern, text)

print m.group()

matchsearch 在匹配失败时返回 None.

match and search return None when they fail to match.

我猜你从 python 得到 AttributeError: 'NoneType' object has no attribute 'group':这是因为你假设你会匹配而不检查 re.match 的返回.

I guess you are getting AttributeError: 'NoneType' object has no attribute 'group' from python: This is because you are assuming you will match without checking the return from re.match.

这篇关于Python正则表达式匹配引号之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆