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] 部分是正确的,但匹配末尾的标点符号是不正确的。

原文由 Ludisposed 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 797
2 个回答

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

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

说明: 其中 ^[A-Z] 在开始时寻找资本

'[^?!.]*' means everything in between start and end is ok except things containing ? or ! or .

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

原文由 Ludisposed 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用下面的正则表达式。

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

工作代码演示

原文由 Chankey Pathak 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题