python - 正则表达式在python中的字符串中查找两个相同的字符串
问题描述
假设我有一个字符串,例如:
..."StringToMatch":{"id":"StringToMatch","This":"SomeRandomThing"...
好吧,它实际上是一个 JSON,但出于其他原因,我想将其视为字符串。我如何找到StringToMatch
使用正则表达式?
我目前正在使用:
value1, value2 = re.findall('"(.*?)":{"id":"(.*?)","This":"SomeRandomThing"', string)[0][:2]
if value1 == value2:
return value1
但这似乎有点“hacky”的方式。有更好的方法吗?
解决方案
利用
"(\w+)":{"id":"\1"
见证明。
解释
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
":{"id":" '":{"id":"'
--------------------------------------------------------------------------------
\1 what was matched by capture \1
--------------------------------------------------------------------------------
" '"'
import re
regex = r'"(\w+)":{"id":"\1"'
test_str = "...\"StringToMatch\":{\"id\":\"StringToMatch\",\"This\":\"SomeRandomThing\"..."
match = re.search(regex, test_str)
if match is not None:
print(match.group(1))
推荐阅读
- postgresql - 如何插入一个空行,但正确进行串行更新?
- javascript - 在新的 DOM 主体中创建和查询元素
- python - 如何减少此函数中的参数数量
- javascript - 用ajax请求填充选择
- javascript - css 样式未在模态对话框中应用 - 我该如何解决?
- orm - 在 ORM Coldfusion 中使用动态生成的实体名称
- debugging - Firefox 开发者工具,同时打开 Inspector & debugger
- node.js - 错误:回调已被调用。当使用异步瀑布并尝试永远运行程序时
- python - 列表不保存其值 - python
- python - 由于 EnvironmentError,spaCy 模型安装失败