def js_replace(text, reg_exp, repl): """Replace `text` with `repl` using Javascript style regular expression to find matches. Args: text (str): String to evaluate. reg_exp (str): Javascript style regular expression. repl (str): Replacement string. Returns: str: Modified string. Example: >>> js_replace('aaBBcc', '/bb/', 'X') 'aaBBcc' >>> js_replace('aaBBcc', '/bb/i', 'X') 'aaXcc' >>> js_replace('aaBBccbb', '/bb/i', 'X') 'aaXccbb' >>> js_replace('aaBBccbb', '/bb/gi', 'X') 'aaXccX' .. versionadded:: 2.0.0 .. versionchanged:: 3.0.0 Reordered arguments to make `text` first. """ text = pyd.to_string(text) if not pyd.is_function(repl): repl = pyd.to_string(repl) return js_to_py_re_replace(reg_exp)(text, repl)
def replace(text, pattern, repl, ignore_case=False, count=0, escape=True): """Replace occurrences of `pattern` with `repl` in `text`. Optionally, ignore case when replacing. Optionally, set `count` to limit number of replacements. Args: text (str): String to replace. pattern (str): String pattern to find and replace. repl (str): String to substitute `pattern` with. ignore_clase (bool, optional): Whether to ignore case when replacing. Defaults to ``False``. count (int, optional): Maximum number of occurrences to replace. Defaults to ``0`` which replaces all. escape (bool, optional): Whether to escape `pattern` when searching. This is needed if a literal replacement is desired when `pattern` may contain special regular expression characters. Defaults to ``True``. Returns: str: Replaced string. Example: >>> replace('aabbcc', 'b', 'X') 'aaXXcc' >>> replace('aabbcc', 'B', 'X', ignore_case=True) 'aaXXcc' >>> replace('aabbcc', 'b', 'X', count=1) 'aaXbcc' >>> replace('aabbcc', '[ab]', 'X') 'aabbcc' >>> replace('aabbcc', '[ab]', 'X', escape=False) 'XXXXcc' .. versionadded:: 3.0.0 """ # pylint: disable=redefined-outer-name text = pyd.to_string(text) if pattern is None: return text pattern = pyd.to_string(pattern) if escape: pattern = re.escape(pattern) if not pyd.is_function(repl): repl = pyd.to_string(repl) flags = re.IGNORECASE if ignore_case else 0 # NOTE: Can't use `flags` argument to re.sub in Python 2.6 so have to use # this version instead. return re.compile(pattern, flags=flags).sub(repl, text, count=count)
def test_is_function(case, expected): assert _.is_function(case) == expected