python - 使用 re.sub() 的输出不正确

标签 python regex

问题陈述:

Inserts an extra space after a period if the period is directly followed by a letter.

下面是代码:

string="This   is  very funny  and    cool.Indeed!"

re.sub("\.[a-zA-Z]", ". ", string)

和输出:

"This is very funny and cool. ndeed!"

它正在替换 '.' 之后的第一个字符。

有什么解决办法吗?

最佳答案

您可以使用positivie lookahead assertion ,它不消耗匹配的部分:

>>> re.sub(r"\.(?=[a-zA-Z])", ". ", string)
'This   is  very funny  and    cool. Indeed!'

替代使用 capturing group and backreference :

>>> re.sub(r"\.([a-zA-Z])", r". \1", string)  # NOTE - r"raw string literal"
'This   is  very funny  and    cool. Indeed!'

仅供引用,您可以使用 \S 而不是 [a-zA-Z] 来匹配非空格字符。

关于python - 使用 re.sub() 的输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26040093/

相关文章:

php - 正则表达式到 preg_replace '\n' 和字符串中的所有其他转义字符?

python - 加权平均值 : Custom layer weights don't change in TensorFlow 2. 2.0

Python:尝试在更改变量时重新计算类属性

c# - 如何检查数字字符串是否在运行序列中

java - 只需要接受 % 符号作为输入字符串

javascript - 如何检查字符串是否不包含除指定字符之外的任何字符

python - 玛雅 2018 Python+QT : Querying Value of Imported TextField

python - 如何在 Python 中显示 SVG 图像

python - 弹丸从曲面弹起-Pygame,Python 3

regex - 什么是上下文无关语法?