开发者

Python re.IGNORECASE being dynamic

I'd like to do something like this:

re.findall(r"(?:(?:\A|\W)" + 'Hello' + r"(?:\Z|\W))", 'hello world',re.I)

And have re.I be dynamic, so I can do case-sensitive or insensitive comparisons on the fly. This works but is undocumented:

re.findall(r"(?:(?:\A|\W)" + 'Hello' + r"(?:\Z|\W))", 'hello world',1)

To set it to sensitive. Is there a Pythonic way to do this? My best thought so far is:

if case_sensitive:
   regex_senstive = 1
else:
   regex_sensitive = re.I
re.findall(r"(?:(?:开发者_如何转开发\A|\W)" + 'Hello' + r"(?:\Z|\W))", 'hello world',regex_sensitive)


To get the default behavior, you can use 0 for the flags parameter. You should not use 1, as it will set the undocumented re.TEMPLATE flag, which disables backtracking.

So you can use:

flags = 0 if case_sensitive else re.I
re.findall(r'pattern', s, flags)

The flags parameter is actually a combination of flags (re.I, re.M, etc.), with each flag represented by a single bit. When no bits are set (the value 0), the default behavior is used.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜