[英]Python regex to match punctuation at end of string
如果句子以大写字母开头并以Python中的[?。!]结尾,我需要匹配。
编辑它必须只在结尾处有[?。!] 但在句子中允许其他标点符号
import re
s = ['This sentence is correct.','This sentence is not correct', 'Something is !wrong! here.','"This is an example of *correct* sentence."']
# What I tried so for is:
for i in s:
print(re.match('^[A-Z][?.!]$', i) is not None)
它不起作用,经过一些更改后,我知道^[AZ]
部分是正确的,但最后匹配标点符号是不正确的。
我让它为自己工作,只是为了澄清或者如果其他人有同样的问题,这就是我的诀窍:
re.match('^[A-Z][^?!.]*[?.!]$', sentence) is not None
说明: ^[AZ]
在开始时查找Capital
'[^?!.]*'
表示开头和结尾之间的所有内容都没问题,除了包含的东西?
或者!
或.
[?.!]$
必须以?
结尾?
或者!
或.
使用下面的正则表达式。
^[A-Z][\w\s]+[?.!]$
正则表达式演示: https : //regex101.com/r/jpqTQ0/2
import re
s = ['This sentence is correct.','this sentence does not start with capital','This sentence is not correct']
# What I tried so for is:
for i in s:
print(re.match('^[A-Z][\w\s]+[?.!]$', i) is not None)
输出:
True
False
False
您的正则表达式检查[AZ]
范围内的单个数字。 你应该改为:
^[A-Z].*[?.!]$
将.*
更改为大写字母和字符串末尾标点符号之间的匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.