Python正则表达式:在句点或逗号后添加空格

9

我有一个字符串如下:

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

我想在句号逗号后面添加一个空格,以便最终结果为:

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

我尝试了这里的解决方案:Python Regex that adds space after dot,但它只对句点逗号有效。我还没有掌握如何让正则表达式同时识别这两个字符。


1
作为一个简单的解决方案,既然您不熟悉正则表达式,为什么不进行两次处理呢?一次处理句号,一次处理逗号。 - Arya McCarthy
你也可以不使用正则表达式来完成它。 - Gahan
2个回答

32

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

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

(?<=[.,])(?=[^\s])
  • (?<=[.,])是正向回顾后发现,匹配句点逗号之后的位置。
  • (?=[^\s])是正向预查,匹配任何非空格的内容。

因此,它将匹配逗号或空格后面的位置,例如ext.Thistext,it,但不匹配word. This

用单个空格()替换。

Regex101演示

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.'

就是这样!谢谢。正则表达式可能让人感到害怕,但它们紧凑而快速。 - maurobio
是的,一旦你掌握了它,你会意识到它们非常简单高效,而且并不可怕。我建议从这里开始(https://www.rexegg.com/),并在学习过程中使用regex101进行实践! - degant
如果句子中包含小数值怎么办? - Madhur Yadav
@degant,为什么在re.sub()中需要r''? - user15479632
@user15479632 因为在Python中“\”字符具有特殊含义。在此处我们正在使用\s,这被识别为异常。使用原始字符串可以解决这个问题。 - EMT
当句子中有小数时,这种方法将无法正常工作。它也会在数字前添加一个空格。 - Idodo

3

如果不想使用正则表达式,也可以按照以下方式解决问题:

>>> 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. '
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接