How can Python regex ignore case inside a part of a pattern but not the entire expression? [duplicate]

故事扮演 提交于 2019-12-19 02:04:19

问题


Say I have a string containing foobar fooBAR FOObar FOOBAR, and I want to search all instances containing a case insensitive "foo" or "FOO" but a lowercase "bar". In this case, re.findall should return ['foobar', 'FOObar'].

The accepted answer for this question explains that it can be done in C# with (?i)foo(?-i)bar, but Python raises an invalid expression error.

Does the Python regex library support such a feature?


回答1:


The re module doesn't support scoped flags, but there's an alternative regex implementation which does:

http://pypi.python.org/pypi/regex




回答2:


Python does not support disabling flags in the same manner; you will have to handle it differently.

>>> re.match('[Ff][Oo]{2}bar', 'Foobar')
<_sre.SRE_Match object at 0x7eff94dac920>


来源:https://stackoverflow.com/questions/6246096/how-can-python-regex-ignore-case-inside-a-part-of-a-pattern-but-not-the-entire-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!