Question related with RE module

Write a Python program that matches a word at the end of string, with optional punctuation ??
and can you please also explain what the meaning with optional punctuation… : )

1 Like

I believe the question asks for a regular expression to find the word at the end of the string, with or without punctuations. the special character “?” matches expression to its left 0 or 1 times. We can make use of that to answer this query. it could be something like this

image

both times , the pattern returns the last word of the sentence with or without punctuation.

2 Likes

could you explain what exactly is ‘(\w+)[.?!]?$’

1 Like

sure.
\w matches every alphanumeric characters in the string. it also matches underscore “_”.
if we enclose any characters within square brackets, it means we are matching only those characters. for example , [123] means we will be matching characters 1, 2, 3 from the string. or [abD] matches a, b, D in the string.
“+” notation is matches the expression to its left 1 or more times.
“?” notation matches the expression to its left 0 or 1 times.
“$” matches the expression to its left at the end of the string.
if we enclose a part of a pattern within (), that part will be returned in the end instead of the whole pattern.

so, to combine all of them, i included \w+ to match the last word. [.!?]? to match the punctuation if it exists. and the $ notation to make sure I’m matching the string at the end.and i enclosed \w+ in () to get the word without the punctuation.
you can practice the above example using or excluding the different notations and understand the use cases of them better.

2 Likes