首页 > 解决方案 > 用另一个替换括号中的字符

问题描述

我需要用其他东西(例如分号)替换所有出现的点,但前提是点是双亲,使用像这样的python:

输入:"Hello (This . will be replaced, this one. too)."
输出:"Hello (This ; will be replaced, this one; too)."

标签: pythonregexstringpython-3.x

解决方案


假设括号是平衡的而不是嵌套的,这里有一个re.split.

>>> import re
>>> 
>>> s = 'Hello (This . will be replaced, this one. too). This ... not but this (.).'
>>> ''.join(m.replace('.', ';') if m.startswith('(') else m
...:        for m in re.split('(\([^)]+\))', s))
...:        
'Hello (This ; will be replaced, this one; too). This ... not but this (;).'

这里的主要技巧是\([^)]+\)用另一对包装正则表达式,()以便保留拆分匹配。


推荐阅读