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.
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
.
>>> 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.