Skip to main content
 首页 » 编程设计

用于行尾的 Python 正则表达式

2024年10月01日29zhenyulu

我正在尝试编写一个在点前后添加空格的正则表达式。 但是,如果点后有空格或行尾,我只需要这个。

但是对于行尾情况,我无法这样做。

Eg. 
 
I want a hotel. >> I want a hotel . 
my email is zob@gmail.com >> my email is zob@gmail.com 
I have to play. bye! >> I have to play . bye! 

以下是我的代码:

# If "Dot and space" after word or number put space before and after 
utterance = re.sub(r'(?<=[a-z0-9])[.][ $]',' . ',utterance) 

如何更正我的正则表达式以确保我上面的第一个示例也有效,我尝试将 $ 符号放在方括号中,但这不起作用。

请您参考如下方法:

主要问题是字符类中的 $ 表示文字 $ 符号,您只需要 grouping construct在这里。

我建议使用以下代码:

import re 
regex = r"([^\W_])\.(?:\s+|$)" 
ss = ["I want a hotel.","my email is zob@gmail.com", "I have to play. bye!"] 
for s in ss: 
    result = re.sub(regex, r"\1 . ", s).rstrip() 
    print(result) 

参见 Python demo .

如果你只需要在行上应用这个而不影响换行符,你可以使用

import re 
regex = r"([^\W_])\.(?:[^\S\n\r]+|$)" 
text = "I want a hotel.\nmy email is zob@gmail.com\nI have to play. bye!" 
print( re.sub(regex, r"\1 . ", text, flags=re.M).rstrip() ) 

参见 this Python demo .

输出:

I want a hotel .  
my email is zob@gmail.com 
I have to play . bye! 

详细信息:

  • ([^\W_]) - 第 1 组匹配任何字母或数字
  • \. - 文字点
  • (?:\s+|$) - 匹配 1+ 个空格或字符串 anchor 结尾的分组(此处,$ 匹配字符串结尾。)

rstrip 将删除替换期间添加的尾随空格。

如果您使用的是 Python 3,[^\W_] 将默认匹配所有 Unicode 字母和数字。在 Python 2 中,re.U 标志将启用此行为。

请注意,最后一个 (?:\s+|$) 中的 \s+ 会将多个空格“收缩”为 1 个空格。