简体   繁体   English

我如何在python regex中找到单引号内的字符串

[英]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的值。

DEMO 演示

>>> 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.

相关问题 如何在Python中的字符串中双引号内显示​​单引号 - How to display single quotes inside double quotes in string in python python-字符串中带有引号的正则表达式 - python - regex with quotes inside of the string python - 如何在单引号内放置参数标记以用于python中的sql参数化查询 - How can I place a parameter marker inside single quotes for sql parameterized query inside python 如何使用python脚本在单引号内提取字符串 - how to extract string inside single quotes using python script 如何判断具有空字符串值的 python 字符串变量在初始化时是使用单引号还是双引号? - How can i tell if a python string variable with an empty string value is using single quotes or double quotes at init time? 使用python,即使字符串使用单引号,我如何检查字符串是否为有效的json对象? - Using python, how can I check if a string is a valid json object, even if the string uses single quotes? Python正则表达式在双引号中查找带有变量的字符串 - Python Regex to find a string with varible in double quotes 我如何使用正则表达式python提取引号内的值? - how do i extract value inside quotes using regex python? 为什么我不能在 Python 中反序列化带有单引号的 JSON 字符串? - Why can I not deserialise a JSON string with single quotes in Python? Python查找用单引号引起来的字符串 - Python find string enclosed in single quotes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM