我想知道一个字符串是否包含“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/