Python正则表达式以匹配字符串结尾的标点符号

2024-10-04 03:18:19 发布

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

如果一个句子以大写字母开头,以[?]结尾,我需要匹配?。!]在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)

它不起作用,经过一些修改后,我知道^[A-Z]部分是正确的,但是匹配结尾的标点符号是不正确的。


Tags: importre编辑foris结尾not大写字母
3条回答

我让它为我自己工作,只是为了澄清,或者如果其他人有同样的问题,这就是我的诀窍:

re.match('^[A-Z][^?!.]*[?.!]$', sentence) is not None

说明: 其中^[A-Z]在开始时查找大写

'[^?!.]*'表示开始和结束之间的所有内容都正常,但包含?!.的内容除外

[?.!]$必须以?!.结尾

使用下面的正则表达式。

^[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

Working code demo

正则表达式检查范围[A-Z]中的单个数字。你应该换成这样:

^[A-Z].*[?.!]$

.*更改为要在字符串末尾的大写字母和标点符号之间匹配的任何内容。

相关问题 更多 >