bjj
bjj

Reputation: 41

python regex with optional multiple groups

I'm trying to match a few patterns and I cannot seem to make it work.

The patterns i'm trying to match are these:

David C. Drummond
Sundar Pichai
Julie Spellman Sweet

I need a regex expression that matches all 3 groups.

What i've tried so far is: r"^(\w*)\W?(\w*|\w\.)\W?(\w*)" with many variations for the space between the words (\s, \b) and with greedy and non greedy symbol(?) after the space.

Upvotes: 0

Views: 670

Answers (1)

Sebastian Proske
Sebastian Proske

Reputation: 8413

For the strings you have shown, you can use ^(\w+)\s+(?:(\w\.|\w+)\s+)?(\w+)$ to match them and have first, middle and last name contained in 3 different groups with the second being optional.

See https://regex101.com/r/O8NniM/1

Upvotes: 1

Related Questions