Python正则表达式在点或逗号后添加空格 [英] Python Regex to add space after dot or comma
问题描述
我有一个字符串如下:
line = "这是一个文本.这是另一个文本,逗号后没有空格."
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 commas, so that the end result is:
newline = "这是一个文本.这是另一个文本,逗号后没有空格."
newline = "This is a text. This is another text, it has no space after the comma."
我从这里尝试了解决方案:Python 正则表达式在点之后添加空格,但它仅适用于点或逗号.我一直无法掌握如何让正则表达式同时识别两个字符.
I tried the solution from here: Python Regex that adds space after dot, but it does work only for dots or commas. I have not been able to grasp how to get the regex recognize both characters at once.
推荐答案
使用此正则表达式匹配前一个字符是点或逗号而下一个字符不是空格的位置:
Use this regex to match locations where preceding character is a dot or a comma and the next character isn't a space:
(?<=[.,])(?=[^\s])
(?<=[.,])
正向后视,寻找点或逗号(?=[^\s])
正向前瞻匹配任何不是空格(?<=[.,])
positive lookbehind that looks for dots or commas(?=[^\s])
positive lookahead that matches anything that isn't a space
所以这将匹配逗号或空格之后的位置,如ext.This
或text,it
.但不是 字.这个
.
So this will match positions just after the comma or the space like ext.This
or text,it
. but not word. This
.
替换为一个空格()
蟒蛇:
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.'
这篇关于Python正则表达式在点或逗号后添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!