Python Regex在点或逗号后添加空格

mau*_*bio 2 python regex

我有一个字符串如下:

line ="这是一个文本.这是另一个文本,逗号后面没有空格."

我想在点逗号之后添加一个空格,以便最终结果是:

newline ="这是一个文本.这是另一个文本,逗号后面没有空格."

我从这里尝试了解决方案:Python Regex在点后添加空格,但它仅适用于点逗号.我无法掌握如何让正则表达式同时识别这两个字符.

deg*_*ant 12

使用此正则表达式匹配前面的字符是点或逗号的位置,下一个字符不是空格:

(?<=[.,])(?=[^\s])
Run Code Online (Sandbox Code Playgroud)
  • (?<=[.,])寻找逗号的正面观察
  • (?=[^\s])积极向前看,匹配任何不是空间的东西

所以这将匹配逗号或空格之后的位置,如ext.Thistext,it.但不是word. This.

替换为单个空格()

Regex101演示

蟒蛇:

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.'
Run Code Online (Sandbox Code Playgroud)