[英]How can i find the string inside single quotes in python regex
I want to match the string inside these lines 我想匹配这些行中的字符串
key: value
key: 'value'
I am using this regex 我正在使用此正则表达式
re.compile(r"(.*key: )(.*)")
but \\2 always catches single quotes as well. 但是\\ 2总是也用单引号引起来。
I tried many things like 我尝试了很多类似的事情
(.*key: )'?(.*)'?
but didn't work 但是没用
I am trying like this 我正在尝试这样
line = regex.sub(r"\1'blah'\2", line)
I think you are trying to capture the value which was not present within the single quotes aswell as the one present within the single quotes. 我认为您正在尝试捕获单引号中不存在的值以及单引号中不存在的值。
key:\s*'?([^'\n]*)'?
Group index 1 contains the value of the field key
. 组索引1包含字段
key
的值。
>>> import re
>>> s = """key: value
... key: 'value'"""
>>> m = re.findall(r"key:\s*'?([^'\n]*)'?", s, re.M)
>>> m
['value', 'value']
import re
s1 = "key: value"
s2 = "key: 'value'"
line = re.search(r'.*key: \'?(.*?)(\'?)$', s1)
print line.group(1) # prints value
line = re.search(r'.*key: \'?(.*?)(\'?)$', s2)
print line.group(1) # prints value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.