首页 » 编程设计

python之在字符串python正则表达式的括号之间找到给定的单词

2024年11月01日22Free-Thinker

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


阅读延展