Sreecharan Desabattula
Sreecharan Desabattula

Reputation: 553

Python regular expression zero or more occurrences

I can\'?t (.*)

My regex is of the above form. But my match object doesn't match if the string given to it ends after t

re.compile(r'I can\'?t (.*)').match(str)

If str = "I cant", it doesn't work. But if str = "I can't use", it works (match returns something).

Upvotes: 3

Views: 5668

Answers (2)

sshashank124
sshashank124

Reputation: 32199

For that you can do:

re.compile(r'I can\'?t.*').match(str)

This will match either "I can't" with some other text following or just "I can't"

Upvotes: 0

Robin
Robin

Reputation: 9644

You left a mandatory space after the t. Remove it and you'll be fine:

I can\'?t(.*)

Also note that the brackets are only useful if you want to use the content of the first capturing group, if not you can safely remove them.

Upvotes: 3

Related Questions