user2750103
user2750103

Reputation: 391

Matching a string Python

So basically I want a program that will only work if the user types something like "I am sick" or "I am too cool" but will not work if they make a typo like "pi am cool".

Here's what I have so far:

text = input("text here: ") 
if re.search("i am", text) is not None:
   print("correct")

So basically, I just need help with if someone types in "Pi am cool" right now it will think that is correct. However I do not want that, I want it so that it has to be exactly "i am cool" however. Since I am creating a ai bot for a school project I need it so the sentence could be "man, I am so cool" and it will pick it up and print back correct, but if it was typed "Man, TI am so cool" with a typo I don't want it to print out correct.

Upvotes: 1

Views: 100

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121186

Use \b word boundary anchors:

if re.search(r"\bi am\b", text) is not None:

\b matches points in the text that go from a non-word character to a word character, and vice-versa, so space followed by a letter, or a letter followed by a word.

Because \b in a regular python string is interpreted as a backspace character, you need to either use a raw string literal (r'...') or escape the backslash ("\\bi am\\b").

You may also want to add the re.IGNORE flag to your search to find both lower and uppercase text:

if re.search(r"\bi am\b", text, re.IGNORE) is not None:

Demo:

>>> re.search(r"\bi am\b", 'I am so cool!', re.I).group()
'I am'
>>> re.search(r"\bi am\b", 'WII am so cool!', re.I) is None
True
>>> re.search(r"\bi am\b", 'I ammity so cool!', re.I) is None
True

Upvotes: 2

Related Questions