[英]using multiple variables with regex in python
I'm trying to search strings with variable using Regular expression operations.我正在尝试使用正则表达式操作搜索带有变量的字符串。
I browsed about it and find this useful code我浏览了它并找到了这个有用的代码
s = "These are oranges and apples and pears, but not pinapples or .."
r = re.compile(r'\bAND\b | \bOR\b | \bNOT\b', flags=re.I | re.X)
r.findall(s)
['and', 'and', 'not', 'or'] #result
In this code they using exact string value 'AND''OR''NOT'.在这段代码中,他们使用精确的字符串值'AND''OR''NOT'。
What should i do if i have something like this,如果我有这样的事情我该怎么办,
a = 'AND'
b = 'OR'
(I'm getting these string values by running a loop) (我通过运行循环来获取这些字符串值)
In this code they are using '|在这段代码中,他们使用'| (or)' and re.findall() , what should i do if i need to search both a and b.
(or)'和re.findall() ,如果我需要同时搜索a 和 b,我该怎么办。 and use re.search()
并使用re.search()
Note: I think i need to use r'\bfoo\b'
because sometimes my matches will be in this way... 'foo.', '(foo)''cod.foo'
注意:我认为我需要使用
r'\bfoo\b'
因为有时我的匹配项会以这种方式... 'foo.', '(foo)''cod.foo'
because of this i can't use condition like if a in s: (or) if a and b in s:
.因此,我不能使用
if a in s: (or) if a and b in s:
之类的条件。
Please give some suggestions to work on this, Thank you.请提出一些建议来解决这个问题,谢谢。
I might not know what you are going to do, but if your intention is to use variables inside regex, then remember that a regex, before it is send to re.compile
, is just a simple text.我可能不知道您要做什么,但如果您打算在正则表达式中使用变量,那么请记住,在发送到
re.compile
之前,正则表达式只是一个简单的文本。 So you can do with it everything you can do with texts like:所以你可以用它来做所有你可以用文本做的事情,比如:
re.compile(f"\\b({a}|{b})\\b")
or in older python:或在较旧的 python 中:
re.compile("\\b(" + a + "|" + b + ")\\b")
You are not restricted to use r"text"
to define regex patterns.您不限于使用
r"text"
来定义正则表达式模式。
If you want to search both variables, you can call re.search twice如果你想搜索两个变量,你可以调用 re.search 两次
Something like this...像这样的东西...
if((re.search(rf"\b(?=\w){(a)}\b(?!\w)", s, re.IGNORECASE)) and (re.search(rf"\b(?=\w){(b)}\b(?!\w)", s, re.IGNORECASE))):
Hope it helps希望能帮助到你
I think you need something like this, and add flag "case insensitive" too:我认为你需要这样的东西,并添加标志“不区分大小写”:
pattern = '\b(and|or|not)\b'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.