Using global flag to compile python RegExp

Is it possible to define a global flag so that Python re.compile()automatically sets it? For example, I want to use the flag re.DOTALLfor all my RegExp in - say - class?

This may seem strange at first, but I can’t control this part of the code because it is generated by YAPPS. I just pass the string containing RegExp to YAPPS and it calls re.compile(). Alas, I need to use it in mode re.DOTALL.

A quick fix is ​​to edit the created parser and add a suitable option. But I still hope for a different and more automatic way to do this.

EDIT: Python allows you to set flags with a (? ...) construct, so in my case re.DOTALL is (? S). Although useful, it does not apply to any class or file.

So my question still remains.

+5
source share
2 answers

Yes, you can change it globally re.DOTALL. But you must not. Global settings are a bad idea in the best of times - this can cause any Python code to be run by the same instance of Python.


So do not do this :

, , Python , - , , . , re.compile -, re.DOTALL.

import re
re.my_compile = re.compile
re.compile = lambda pattern, flags: re.my_compile(pattern, flags | re.DOTALL)

.

, :

from contextlib import contextmanager

@contextmanager
def flag_regexen(flag):
    import re
    re.my_compile = re.compile
    re.compile = lambda pattern, flags: re.my_compile(pattern, flags | flag)
    yield
    re.compile = re.my_compile

with flag_regexen(re.DOTALL):
    <do stuff with all regexes DOTALLed>
+10

:

r"(?s)Your.*regex.*here"
+7

All Articles