我想去掉另一个单词之后的空格、括号和字符。例如,
- 你好(嗨)->你好
- 你好(嗨)->你好
- 你好(嗨)bonjour -> 你好
- (嗨)你好,你好 ->(嗨)你好,你好
- (嗨)_你好 -> (嗨)_你好
我已经成功地去掉了空格和括号,但是当它位于单词的开头时我无法阻止它。
re.sub("\s*\(.+", "", "hello(hi)") # 'hello'
re.sub("\s*\(.+", "", "(hi)_hello") # '', NOT desirable
re.sub("\w+\s*\(.+", "", "hello(hi)") # '', NOT desirable
re.sub("\w+\s*\(.+", "", "(hi)_hello") # '(hi)_hello'
我也查了一些关于负向前瞻的文档,但到目前为止还找不到。
感谢您的帮助。
最佳答案
您可以使用带有负向后查找的正则表达式。
cases = [
'hello (hi)',
'hello(hi)',
'hello (hi) bonjour',
'(hi) hello bonjour',
'(hi)_hello'
]
>>> [re.sub(r'(?<!^)\s*\(.*', '', i) for i in cases]
['hello', 'hello', 'hello', '(hi) hello bonjour', '(hi)_hello']
详细信息
(?<! # negative lookbehind
^ # (do not) match the start of line
)
\s* # 0 or more spaces
\( # literal parenthesis
.* # match 0 or more characters (greedy)
关于python - 当模式存在时匹配字符串(以模式开头除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49792965/