regex_functions: Add regex_sub

This implements %regex_sub built-in function to enhance
string-processing capabilities, allowing users to perform substitutes
like:
* removing non-ascii characters
* replacing subsequent whitespace characters with a single whitespace
This commit is contained in:
Tomas Babej 2024-04-25 21:05:09 -04:00
parent ec58a80660
commit 20a94d9a4f

View file

@ -52,3 +52,13 @@ class RegexFunctions:
Returns number of capture groups in regex Returns number of capture groups in regex
""" """
return Integer(re.compile(regex.value).groups) return Integer(re.compile(regex.value).groups)
@staticmethod
def regex_sub(regex: String, replacement: String, string: String) -> String:
"""
:description:
Returns the string obtained by replacing the leftmost non-overlapping occurrences of the
pattern in string by the replacement string. The replacement string can reference the
match groups via backslash escapes. Callables as replacement argument are not supported.
"""
return String(re.sub(regex.value, replacement.value, string.value))