1

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.

1 Answer 1

1

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.")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.