Python regex to match punctuation at end of string

后端 未结 3 1794
伪装坚强ぢ
伪装坚强ぢ 2021-02-15 17:40

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

EDIT It must have [?.!] only at end but allo

3条回答
  •  盖世英雄少女心
    2021-02-15 17:48

    Use the below regex.

    ^[A-Z][\w\s]+[?.!]$
    

    Regex demo: 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)
    

    Output:

    True
    False
    False
    

    Working code demo

提交回复
热议问题