Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中使用正则表达式在双引号之间获取最右边的字符和文本_Python_Regex - Fatal编程技术网

如何在Python中使用正则表达式在双引号之间获取最右边的字符和文本

如何在Python中使用正则表达式在双引号之间获取最右边的字符和文本,python,regex,Python,Regex,我有一个python列表,其中包含以下内容: ['"Some-text" {12345-ab123-cd456}', '"Some-Another-text2" {54321-ab123-cd456}]' 我希望得到的结果是: text, 12345-ab123-cd456 text2, 54321-ab123-cd456 到目前为止,我已使用re模块从{}获取信息: re.compile(r'.*{(.*)} 我想做的是在双引号内的“-”之后获取最右边的文本,添加逗号并获取花括号内的信息

我有一个python列表,其中包含以下内容:

['"Some-text" {12345-ab123-cd456}', '"Some-Another-text2" {54321-ab123-cd456}]'
我希望得到的结果是:

text, 12345-ab123-cd456
text2, 54321-ab123-cd456
到目前为止,我已使用re模块从{}获取信息:

re.compile(r'.*{(.*)}

我想做的是在双引号内的“-”之后获取最右边的文本,添加逗号并获取花括号内的信息。我能一步完成所有这些吗?在一个正则表达式中?或者什么是最好的方法呢?

我认为正则表达式是解决这个问题的好方法,如果您最初将这些数据作为字符串提供,就像您发布的一样

在已有的基础上进行扩展

>>> import re
>>> pattern = re.compile(r'\-([^\-]*)"\s+{(.*)}')
>>> m = pattern.search('"Some-Another-text2" {54321-ab123-cd456}]')
>>> m.groups()
('text2', '54321-ab123-cd456')

使用此选项,您可以循环浏览数据和模式。搜索每个字符串。

或者,使用更简单的模式:

import re
outlist = []
pat = re.compile('".*-(\w+)" {(.*)}', re.I)
for s in ['"Some-text" {12345-ab123-cd456}', '"Some-Another-text2" {54321-ab123-cd456}']:     
    m = re.match(pat, s)
    out = m.group(1) + ", "+ m.group(2)
    print(s)
    print(out)
    outlist.append(out)

print(outlist)
产生:

"Some-text" {12345-ab123-cd456}
text, 12345-ab123-cd456
"Some-Another-text2" {54321-ab123-cd456}
text2, 54321-ab123-cd456
['text, 12345-ab123-cd456', 'text2, 54321-ab123-cd456']
输出:

text, 12345-ab123-cd456                                                                                       
text2, 54321-ab123-cd456   

和@Kasra一样,我想知道这个解决方案有什么问题。好的,我写了一个完整的答案!你只需要保留
文本
text2
哦,我错过了!再次感谢!为什么要在循环中重新编译正则表达式模式?这就是重新编译函数的要点。。。你可以编译并使用它。我没有注意到他想从文本中删掉这一部分,所以这里有一个固定的正则表达式,我将在
{}
附近添加
\s*
,因为如果括号内的模式以空格开头,你的正则表达式将失败。非常感谢!我正在使用子流程模块将流程输出读入一个列表,然后在这个列表上使用正则表达式,正如您所示。但是,在我打印列表时,它位于一个额外的括号内(如:[[““Text”{12354-45123}',““Text2”{12345-2435}]”)。我想我可以很容易地删除这些括号?另一个选项:m=re.match(““*-(.*)”\s*{(.*)}”,““另一个文本”{54321-ab123-cd456}”)
text, 12345-ab123-cd456                                                                                       
text2, 54321-ab123-cd456