python - 当模式存在时匹配字符串(以模式开头除外)

标签 python regex

我想去掉另一个单词之后的空格、括号和字符。例如,

  • 你好(嗨)->你好
  • 你好(嗨)->你好
  • 你好(嗨)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/

相关文章:

python - 可能的 math.ceil() 错误

python - 用 BeautifulSoup 替换内部 HTML?

python - 名称错误 : name 'pydotplus' is not defined

Javascript RegExp + 单词边界 + unicode 字符

python - 处理生成器中抛出的异常

java - 可以简化标准输出和标准输入通信

javascript - Instagram 的正则表达式无法按预期工作

在循环中选择第一个出现的数字的正则表达式

javascript - 在 Javascript 中将 $(美元符号)添加到多个数字

Xcode : exclude matches from result set? 中的正则表达式