Sachin Muthumala
Sachin Muthumala

Reputation: 765

How to fix this python problem with regex?

Consider the Python program below.

import re
  words = input("Say something!\n")
  p = re.compile("my name is (.*)", re.IGNORECASE)
  matches = p.search(words)
  if matches:
    print(f"Hey, {matches[1]}.")
  else:
    print("Hey, you.")

Given input like My name is Earl, this program politely outputs Hey, Earl. Given input like My name is Earl Hickey, though, this program outputs Hey, Earl Hickey, which feels a bit formal. Propose how to modify the argument to re.compile in such a way (without hardcoding Earl) that this program would instead output Hey, Earl in both cases.

Upvotes: 1

Views: 60

Answers (1)

ggorlen
ggorlen

Reputation: 56955

You can use r"my name is (\w+)". \w+ restricts the capture group to a sequence of word characters, so we'll make the assumption that everything up until the end of the word is the first name.

import re

words = input("Say something!\n")
matches = re.search(r"my name is (\w+)", words, re.I)

if matches:
    print(f"Hey, {matches[1]}.")
else:
    print("Hey, you.")

Upvotes: 1

Related Questions