【问题标题】:Adding a space after a special character在特殊字符后添加空格
【发布时间】:2022-01-02 22:26:43
【问题描述】:

如果字符串中还没有特殊字符,我会尝试在特殊字符后添加一个空格。

这是我的代码

import re
line='Hello there! This is Robert. Happy New Year!Are you surprised?Im not.'
for i in re.finditer(r"\?|!|\.", line):
if line[i.end()]!=' ':
    line=line.replace(line[i.end()],line[i.end()]+' ')

预期输出:

"Hello there! This is Robert. Happy New Year! Are you surprised? Im not."

我的代码输出:

"Hello t here!  This is Robert . Happy New Year!A re you surprised? Im not ."

我还没弄清楚为什么它不起作用。

【问题讨论】:

  • 我认为您的代码与结果无关。因为t 被替换为t 。所以我怀疑你在真实代码中使用了t

标签: python regex string


【解决方案1】:

使用

re.sub(r'([!?.])(?=\S)', r'\1 ', line)

regex proof

解释

--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [!?.]                    any character of: '!', '?', '.'
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    \S                       non-whitespace (all but \n, \r, \t, \f,
                             and " ")
--------------------------------------------------------------------------------
  )                        end of look-ahead

Python code

import re
line='Hello there! This is Robert. Happy New Year!Are you surprised?Im not.'
line = re.sub(r'([!?.])(?=\S)', r'\1 ', line)

结果Hello there! This is Robert. Happy New Year! Are you surprised? Im not.

【讨论】:

    【解决方案2】:

    您可以对re.sub 使用以下正则表达式,将(零宽度)匹配项替换为一个空格:

    (?<=[!?.])(?=\S)
    

    (?&lt;=[!?.])negative lookbehind 断言字符串位置前面是给定字符类中的三个字符之一,positive lookahead @987654325 @ 断言当前字符串位置后跟一个不是空格的字符。

    Demo

    【讨论】:

      【解决方案3】:

      在您的模式中,您使用 3 个字符 \?|!|\. 的交替,也可以在单个字符类中 [?!.]

      你可以做的是匹配其中任何一个,并在其后声明一个非空白字符而不是任何这些字符,以防你有例如Hi!!

      在替换中,您可以使用 \g&lt;0&gt; 后跟空格的完整匹配。

      [?!.](?=[^?!.\s])
      

      模式匹配

      • [?!.] 匹配 ! . ?
      • (?= 正向前瞻,断言右边是
        • [^?!.\s]匹配除!以外的非空白字符@.?
      • ) 关闭前瞻

      查看regex demoPython demo

      示例

      import re
      
      regex = r"[?!.](?=[^?!.\s])"
      line = 'Hi!!Hello there! This is Robert. Happy New Year!Are you surprised?Im not.'
      result = re.sub(regex, r'\g<0> ', line)
      
      if result:
          print(result)
      

      输出

      Hi!! Hello there! This is Robert. Happy New Year! Are you surprised? Im not.
      

      【讨论】: