【发布时间】:2020-08-12 06:14:18
【问题描述】:
我想检测 标点符号之后的缺失空格和 标点符号之前的额外空格。我尝试使用正则表达式来匹配[A-Za-z0-9][?.,:!][A-Z] 和[A-Za-z0-9]\s+[?.,:!],但是当应用于字符串Something is in the air tonight.Or is it ? 时,这两个都返回None。
import re
mystring = "Something is in the air tonight.Or is it ?"
missing_space_regex = re.compile('[A-Za-z0-9][?.,:!][A-Z]')
print(missing_space_regex.match(mystring))
extra_space_regex = re.compile('[A-Za-z0-9]\s+[?.,:!]')
print(extra_space_regex.match(mystring))
我意识到上面的 extra_space_regex 不会检测到文本以标点符号开头的情况,但我可以将其作为特殊情况处理。
【问题讨论】:
-
这不是您的直接问题。但是在第二个打印中,您使用的是第一个正则表达式而不是第二个。
-
@Rashid'Lee'Ibrahim:感谢您指出这一点。已更正。
标签: python-3.x string punctuation