Resnad
Resnad

Reputation: 35

How can I select this specific part of a string using regex?

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!

Upvotes: 1

Views: 74

Answers (4)

PJProudhon
PJProudhon

Reputation: 825

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

Upvotes: 0

yatu
yatu

Reputation: 88305

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'

Upvotes: 1

DirtyBit
DirtyBit

Reputation: 16792

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

Upvotes: 0

hamza tuna
hamza tuna

Reputation: 1497

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

results:

'test'

Upvotes: 0

Related Questions