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

2024-05-19 12:03:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根绳子如下:

line=“这是一个文本。这是另一个文本,逗号后没有空格。”

我想在点逗号后面加一个空格,这样最终的结果是:

newline=“这是文本。这是另一个文本,逗号后没有空格。”

我从这里尝试了解决方案:Python Regex that adds space after dot,但它只对点逗号有效。我无法掌握如何让regex同时识别这两个字符。


Tags: 文本thatlinenewlinespace解决方案字符dot
1条回答
网友
1楼 · 发布于 2024-05-19 12:03:18

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

(?<=[.,])(?=[^\s])
  • (?<=[.,])正向查找后面的逗号
  • (?=[^\s])与任何不是空格的内容匹配的正向展望

所以这将匹配逗号后面的位置,或者像ext.Thistext,it这样的空格。但不是word. This

替换为单个空格(

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.'
网友
2楼 · 发布于 2024-05-19 12:03:18

或者,也可以不使用regex来解决您的问题,如下所示:

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

相关问题 更多 >

    热门问题