【问题标题】:Regex - Remove space between two punctuation marks but not between punctuation mark and letter正则表达式 - 删除两个标点符号之间的空格,但不删除标点符号和字母之间的空格
【发布时间】:2020-07-09 03:56:45
【问题描述】:

我有以下正则表达式用于删除标点符号之间的空格。

re.sub(r'\s*(\W)\s*', r'\1', s)

在我的几乎所有测试用例中都可以正常工作,除了这个:

This is! ? a test! ?

我需要的

This is!? a test!?

得到

This is!?a test!?

如何不删除 ? 和“a”之间的空格?我错过了什么?

【问题讨论】:

  • re.sub(r'\s*(\W)', r'\1', s)
  • 感谢您的评论,这将使其他测试失败This is a! ? test! ? (末尾有一个空格。但我仍然可能想调用 strip()
  • 首先要做的是使用比\W 更具体的字符类。 (最后是\s,这取决于你想做什么)。
  • 你应该看看lookaheads和lookbehinds断言。
  • 如果你不想匹配换行符可能这样(?<=[?!])[^\S\r\n]+(?=[!?])regex101.com/r/CoBw69/1

标签: python regex


【解决方案1】:

试试这个:

string = "This is! ? a test! ?"
string = re.sub(r"(\W)\s*(\W)", r"\1\2", string)
print(string)

输出:

This is!? a test!?

【讨论】:

    【解决方案2】:

    这应该可行:

    import re
    
    str = 'This is! ? a test! ?'
    res = re.sub(r'(?<=[?!])\s+(?=[?!])', '', str)
    print(res)
    

    输出:

    This is!? a test!?
    

    说明:

    (?<=[?!])   # positive lookbehind, make sure we have a punctuation before (you can add all punctuations you want to check)
    \s+         # 1 or more spaces
    (?=[?!])    # positive lookahead, make sure we have a punctuation after
    

    【讨论】:

      【解决方案3】:

      为了在 Python 中匹配标点字符和正则表达式,您可以使用 (?:[^\w\s]|_) 模式,它匹配除字母、数字或空格以外的任何字符

      因此,您需要匹配一个或多个空格 (\s+),其前面紧跟一个标点符号 ((?&lt;=[^\w\s]|_)),后面紧跟这样一个字符 ((?=[^\w\s]|_)):

      (?<=[^\w\s]|_)\s+(?=[^\w\s]|_)
      

      请参阅online regex demo

      Python demo:

      import re
      text = "This is! ? a test! ?"
      print( re.sub(r"(?<=[^\w\s]|_)\s+(?=[^\w\s]|_)", "", text) )
      # => This is!? a test!?
      

      【讨论】:

        【解决方案4】:

        另一种选择是利用PyPi regex module 使用\p{Punct} 在正向环顾中匹配标点符号。

        Python demo

        例如

        import regex
        
        pattern = r"(?<=\p{Punct})\s+(?=\p{Punct})"
        s = 'This is! ? a test! ?'
        
        print(regex.sub(pattern, '', s))
        

        输出

        This is!? a test!?
        

        请注意,\s 也可以匹配换行符。您还可以使用 [^\S\r\n] 匹配除换行符以外的空白字符。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-24
          • 1970-01-01
          相关资源
          最近更新 更多