1

Hi and thank you for your time.

I have the following example string: "Hola Luis," but the string template will always be "Hola {{name}},".

How would the regex be to match any name? You can assume the name will follow a blank space and "Hola" before that and it will have a comma right after it.

Thank you!

1
  • 1
    It would have been nice to show us what you tried before ask for help. Commented Mar 6, 2019 at 11:02

4 Answers 4

1

You can use the following regular expression, assuming that as you mention, the format is always the same:

import re
s = "Hola Luis,"
re.search('Hola (\w+),', s).group(1)
# 'Luis'
Sign up to request clarification or add additional context in comments.

Comments

0
s = 'Hola test'
re.match(r'Hola (\w+)', s).groups()[0]

results:

'test'

3 Comments

how it different from @yatu solution
i didnt saw it when writing.
@ you have to change 'Hola (\w+)' to `'Hola (\w+),' as mention by OP, STRUCTURe there
0

Continuing from @yatu,

Without regex:

print("Hola Luis,".split(" ")[1].strip(","))

Explanation:

split(" ") # to split the string with spaces 
[1]        # to get the forthcoming part
strip(",") # to strip off any ','

OUTPUT:

Luis

Comments

0

According to Falsehoods Programmers Believe About Names and your requirements, I'll use the following regex: (?<=Hola )[^,]+(?=,).

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.