python - 在Python中检索括号中的第一个单词
问题描述
我在此处搜索并阅读了一些代码正则表达式以返回括号之间的文本
但是例如说我有以下字符串
“[指南] 力量(STR)推荐给勇士(勇士 -> 狂战士)”
我将如何仅输出“STR”而不输出 (Warriors -> Berserker) ?
谢谢!
解决方案
考虑以下字符串,
s = 'I am John (John (M) Doe)'
有效括号中的第一个单词应该是“John (M) Doe”而不是“John (M”。以下代码将计算开括号和闭括号:
opn = 0
close = 0
new_str = ''
add = False
for i in s:
if not add:
if i == '(':
opn += 1
add = True
else:
if i == '(':
new_str += i
opn += 1
elif i == ')':
close += 1
if opn == close:
break
else:
new_str += i
else:
new_str += I
print(new_str)
这产生:
John (M) Doe
希望这可以帮助!
推荐阅读
- python - 搜索此字符串并捕获名称
- javascript - 将 JS / Leaflet 动画的数据流捕获为 MP4
- python-3.x - 如何使 cv2.videoCapture.read() 更快?
- python - python - 更新字典的值
- memory - Wasm 热重载实验:揭穿假设,以及如何指定数据部分的位置?
- javascript - 如何在 React.JS 中使用“onclick”功能更改特定 div 的背景图像
- swift - Swift 计时器方法提前终止应用程序并出现 SIGABRT 错误
- python - 为什么python比matlab慢?
- amazon-web-services - 客户端计算机上的“puppet agent --test”没有从 Puppet 主服务器获取清单
- java - 处理结果集时出现死锁