An optimal and robust implementation of a Jinja2 regex filter.
(s, find, replace)
| 39 | return ' '.join(capitalize_first_letter(word) for word in s.split()) |
| 40 | |
| 41 | def regex_replace(s, find, replace): |
| 42 | """An optimal and robust implementation of a Jinja2 regex filter.""" |
| 43 | if not isinstance(s, str): |
| 44 | logging.error("Input must be a string.") |
| 45 | return s |
| 46 | if not isinstance(find, str) or not find.strip(): |
| 47 | logging.error("Regex pattern must be a non-empty string.") |
| 48 | return s |
| 49 | if not isinstance(replace, str): |
| 50 | logging.error("Replacement must be a string.") |
| 51 | return s |
| 52 | try: |
| 53 | pattern = re.compile(find) |
| 54 | return pattern.sub(replace, s) |
| 55 | except re.error as e: |
| 56 | logging.error(f"Invalid regex pattern: {find}. Error: {e}") |
| 57 | return s |
| 58 | |
| 59 | def format_list(list_, pattern): |
| 60 | """ Formats a list of strings using a given pattern. |
nothing calls this directly
no outgoing calls
no test coverage detected