from typing import Union
from typing import Pattern
import re


def compile_regex(regex: Union[str, Pattern[str]], flags: int = 0) -> Pattern[str]:
    """Compile the regex string/object into a object with the given flags."""
    if isinstance(regex, Pattern):
        if regex.flags == flags:
            return regex
        regex = regex.pattern
    return re.compile(regex, flags)