构建复杂的单行正则表达式字符串。
项目描述
正则表达式构建
构建复杂的单行正则表达式字符串。
RegexBuild构建的首选方式是在实例上使用单行调用链。对于更复杂的情况,将其用作上下文管理器将允许在同一实例上进行多次调用。
的实例RegexBuild可以与字符串互换使用,允许使用多个嵌套实例。
>>> original_regex = r'.*\\Roaming\\(Microsoft|NVIDIA|Adobe\\.*(Asset|Native)Cache)\\'
# Complex example
>>> with RegexBuild(r'.*\\Roaming\\') as build_regex:
... build_regex(
... 'Microsoft', 'NVIDIA', RegexBuild(r'Adobe\\.*')('Asset', 'Native')('Cache'),
... )(r'\\')
>>> original_regex == str(build_regex)
True
# Different ways to build the same regex
>>> with RegexBuild('(?i)', exit='$') as case_insensitive:
... # As one line
... case_insensitive('prefix1_')('word1', 'word2')('_suffix1')
...
... # As context managers
... with case_insensitive('prefix2_') as prefix:
... with prefix('word2', 'word3') as words:
... words('_suffix2')
...
... # As context manager using the "end" parameter
... with case_insensitive('prefix3_', end='_suffix3') as prefix:
... prefix('word4')
... prefix('word5')
...
>>> case_insensitive
'(?i)(prefix1_(word1|word2)_suffix1|prefix2_(word3|word4)_suffix2|prefix3_(word5|word6)_suffix3)$'