python - 在字符串 python regex 中查找括号之间的给定单词

标签 python regex string cpu-word

我想知道一个字符串是否包含“randomize”这个词。这个词可能存在于字符串的括号内和之外,但我只对这个词存在于括号内的情况感兴趣。

mystring = "You said {single order='randomize'} that P.E is...Why?"

我知道我必须为此使用正则表达式,但到目前为止我的尝试失败了。

本质上我想说的是:

look for "randomize" and check if its in brackets. 

谢谢

最佳答案

您可以使用一些否定类:

>>> import re
>>> mystring = "You said {single order='randomize'} that P.E is...Why?"
>>> if mystring.find("randomize") != -1:
...     if re.search(r'{[^{}]*randomize[^{}]*}', mystring):
...         print("'randomize' present within braces")
...     else:
...         print("'randomize' present but not within braces")
... else:
...     print("'randomize' absent")

# => 'randomize' present within braces

关于python - 在字符串 python regex 中查找括号之间的给定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21785004/

相关文章:

regex - 用 perl 解析 scutil 输出

javascript - 突出显示与 Perl 正则表达式匹配的 HTML 部分 - 在服务器端 Perl 或客户端 javascript 中执行吗?

c# - 连字符前后的正则表达式模式匹配

c# - 首先拆分然后加入字符串的子集

python codefights Count The Black Boxes,建模矩形的对角线

python - Python 中的正则表达式

python - 我的 Python 程序很慢!我怎样才能加快速度?难道我做错了什么?

python - 使用 BeautifulSoup 获取日期

javascript - 如何使用 javascript 动态添加属性

java - 是否有一个 java 库可以将描述时间度量的字符串(例如 "1d 1m 1s")转换为毫秒?