Python Regex to add space after dot or comma

后端 未结 2 1868
你的背包
你的背包 2021-01-06 10:47

I have a string as follows:

line = \"This is a text.This is another text,it has no space after the comma.\"

I want to add a space after dots and

相关标签:
2条回答
  • 2021-01-06 11:06

    alternatively your can also be solved without regex as follow :

    >>> line = "This is a text.This is another text,it has no space after the comma."
    >>> line.replace('.', '. ', line.count('.')).replace(',', ', ', line.count(','))
    'This is a text. This is another text, it has no space after the comma. '
    >>> 
    
    0 讨论(0)
  • 2021-01-06 11:14

    Use this regex to match locations where preceding character is a dot or a comma and the next character isn't a space:

    (?<=[.,])(?=[^\s])
    
    • (?<=[.,]) positive lookbehind that looks for dots or commas
    • (?=[^\s]) positive lookahead that matches anything that isn't a space

    So this will match positions just after the comma or the space like ext.This or text,it. but not word. This.

    Replace with a single space ()

    Regex101 Demo

    Python:

    line = "This is a text.This is another text,it has no space after the comma."
    re.sub(r'(?<=[.,])(?=[^\s])', r' ', line)
    
    // Output: 'This is a text. This is another text, it has no space after the comma.'
    
    0 讨论(0)
提交回复
热议问题