Python正则表达式匹配引号中包含的关键字,然后是引号中包含的另一个关键字

Python正则表达式匹配引号中包含的关键字,然后是引号中包含的另一个关键字,python,regex,Python,Regex,我是python新手,正在尝试使用正则表达式来匹配字符串 string = '"formula_pretty":"MoS2"' whatIsee =re.search(r'(?<="formula_pretty":").+(?= \")',string.group(0) print(whatIsee) string=''formula_pretty:“MoS2”' whatIsee=re.search(r’)你可以试试这个伴侣 (?<="formula_pretty":").+(?

我是python新手,正在尝试使用正则表达式来匹配字符串

string = '"formula_pretty":"MoS2"'
whatIsee =re.search(r'(?<="formula_pretty":").+(?= \")',string.group(0)
print(whatIsee)
string=''formula_pretty:“MoS2”'

whatIsee=re.search(r’)你可以试试这个伴侣

(?<="formula_pretty":").+(?=")

(?前瞻组
(?=\”)
中只有一个额外的空格会导致不匹配。只要这样做,您就不必转义
,因为您总是使用原始字符串

s = '"formula_pretty":"MoS2", "somethingelse":"blabla"'
whatIsee = re.search(r'(?<="formula_pretty":").+?(?=")', s)
print(whatIsee.group())
string=''formula_pretty:“MoS2”'

match=re.search(r’(?但在这里,当我不转义时,它会抛出错误
。我可以知道为什么我不太了解正则表达式的python风格吗?@CodeManiac:只有在不使用原始字符串时才需要转义。但是由于OP已经使用原始字符串,所以不需要转义。
r
在字符串使python中的字符串变为原始字符串之前。@CodeManiac您可以更改r。”“to r”,只需在regex101中单击它。非常感谢@PushpeshKumarRajwanshi!您的解决方案肯定有效。但是,我注意到,.+(?=\)是从字符串的后面搜索“from”。例如,如果字符串=”“formula_pretty”:“MoS2”,“somethingelse”:“blablabla”'输出将是MoS2”,“somethingelse”“:blabla而不是MoS2。我如何要求输出仅为MoS2?@PushpeshKumarRajwanshi在我完成编辑我的问题之前,您的答复就来了哈哈。它很有效!非常感谢!解释、发布的代码的作用以及它如何解决问题,很少无法改进答案。
MoS2
string = '"formula_pretty":"MoS2"'
match = re.search(r'(?<=:)\s*"(.+?)"', string).group(1)