9

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)

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

Valeriy
  • 1,365
  • 3
  • 18
  • 45
Ludisposed
  • 1,709
  • 4
  • 18
  • 38

3 Answers3

19

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

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

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

[?.!]$ must end with ? or ! or .

Ludisposed
  • 1,709
  • 4
  • 18
  • 38
  • 1
    Using a negative look-ahead followed by `.` is an intricate and probably inefficient way of achieving that. Consider using a negative character class: `[^?!.]*`. – lenz May 03 '17 at 08:49
2

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

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
1

Your regex checks for a single digit in the range [A-Z]. You should change to something like:

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

Change the .* to whatever you want to match between the capital letter and the punctuation at the end of the string.

Maroun
  • 94,125
  • 30
  • 188
  • 241