Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.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_Re - Fatal编程技术网

正则表达式在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))