Python regex匹配字符串末尾的标点符号 [英] Python regex to match punctuation at end of string

查看:104
本文介绍了Python regex匹配字符串末尾的标点符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果句子在Python中以大写字母开头并以[?.!]结尾,我需要匹配.

I need to match if a sentence starts with a capital and ends with [?.!] in Python.

编辑 必须在末尾仅使用[?.!] ,但允许在句子中使用其他标点符号

EDIT It must have [?.!] only at end but allow other punctuation in the sentence

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

It does not work, after some changes I know the ^[A-Z] part is correct but matching the punctuation at the end is incorrect.

推荐答案

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

I made it working for myself, and just for clarification or if other people have the same problem this is what did the trick for me:

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

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

Explanation: Where ^[A-Z] looks for a Capital at start

'[^?!.] *'表示开始和结束之间的所有内容都可以,除了包含?或<代码>.

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

[?.!] $ 必须以?.

这篇关于Python regex匹配字符串末尾的标点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆