Hi Friends I'm trying to include "or |" condition in search pattern using re.search. Can someone help me how to achieve or condition as I'm not getting match. Below code works
嗨朋友我想包括“或|”使用re.search搜索模式中的条件。有人可以帮助我如何实现或条件,因为我没有得到匹配。下面的代码工作
>>> pattern = re.escape('apple.fruit[0]')
>>> sig = 'apple.fruit[0]'
>>> if re.search(pattern, sig):
... print("matched")
...
matched
>>> pattern = re.escape('apple.fruit[0] or vegi[0]')
>>> if re.search(pattern, sig):
... print("matched")
...
>>>
I want to match above string "apple." followed by fruit[0] or vegi[0]
我想匹配上面的字符串“apple”。其次是水果[0]或vegi [0]
1 个解决方案
#1
1
Regex or should be achieved through |
operator and we don't inculde this inside re.escape
. If you do so, then it would loose it's special meaning.
正则表达式还是应该通过|来实现运算符,我们不会在re.escape中包含这个内容。如果你这样做,那么它将失去它的特殊含义。
pattern = re.escape('apple.fruit[0]')+ '|' + re.escape('vegi[0]')
or
要么
pattern = r'apple\.fruit\[0\]|vegi\[0\]'
#1
1
Regex or should be achieved through |
operator and we don't inculde this inside re.escape
. If you do so, then it would loose it's special meaning.
正则表达式还是应该通过|来实现运算符,我们不会在re.escape中包含这个内容。如果你这样做,那么它将失去它的特殊含义。
pattern = re.escape('apple.fruit[0]')+ '|' + re.escape('vegi[0]')
or
要么
pattern = r'apple\.fruit\[0\]|vegi\[0\]'