Skip to content

Instantly share code, notes, and snippets.

@jinstrive
Created October 22, 2015 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jinstrive/45617d8654963d62d2a7 to your computer and use it in GitHub Desktop.
Save jinstrive/45617d8654963d62d2a7 to your computer and use it in GitHub Desktop.
python string operate, replace string in Regular Expression.
def replace_matched_part(pattern, lstring, repl_str, group_name):
"""
:param pattern: 类似 '.*?_(?P<char>\w)_\d\.\w+$'
:param lstring: 需要替换的字符串
:param repl_str: 匹配部分替换成的字符串
:param group_name: 匹配中的组名 char
:return:
"""
def _rep_func(m):
return ''.join([m.string[:m.start(group_name)], repl_str, m.string[m.end(group_name):]])
return re.sub(pattern, _rep_func, lstring)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment