正则表达式在python中的字符串中查找两个相同的字符串
假设我有一个字符串,如:正则表达式在python中的字符串中查找两个相同的字符串,python,regex,re,Python,Regex,Re,假设我有一个字符串,如: ..."StringToMatch":{"id":"StringToMatch","This":"SomeRandomThing"... 实际上,它是一个JSON,但出于其他原因,我想将其视为字符串。如何使用正则表达式查找StringToMatch 我目前正在使用: value1, value2 = re.findall('"(.*?)":{&quo
..."StringToMatch":{"id":"StringToMatch","This":"SomeRandomThing"...
实际上,它是一个JSON,但出于其他原因,我想将其视为字符串。如何使用正则表达式查找StringToMatch
我目前正在使用:
value1, value2 = re.findall('"(.*?)":{"id":"(.*?)","This":"SomeRandomThing"', string)[0][:2]
if value1 == value2:
return value1
但这似乎有点“老套”的做法。有更好的方法吗?使用
(\w+):{“id”:“\1”
看
解释
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
(组和捕获到\1:
--------------------------------------------------------------------------------
\w+字字符(a-z,a-z,0-9,41;)(1或
更多次(与最多金额匹配)
(可能的)
--------------------------------------------------------------------------------
)结束\1
--------------------------------------------------------------------------------
“:{id:”:{id:“'
--------------------------------------------------------------------------------
\1与捕获匹配的内容\1
--------------------------------------------------------------------------------
" '"'
:
重新导入
regex=r'(\w+):{“id”:“\1”
test\u str=“…\”StringToMatch\”:{“id\”:“StringToMatch\”,“This\”:“SomeRandomThing\”…”
匹配=重新搜索(regex,test_str)
如果匹配项不是无:
打印(匹配组(1))