Klendathu
Klendathu

Reputation: 793

Regex to get last name from a string

So I have names in strings, and I need to extract the last name. The names come in these formats:

Mr. Firstname MI. Lastname (Designator)

and

Mr. Firstname (Nick) MI. Lastname (Designator)

The current regex I have checks for the existence of the "(" character, and gets the word character before it (LastName).

(/\\w+ ["("]/)

However, for names in the 2nd format, it returns the Firstname. I need the regex to work backwards from the end of the string, find the first "(", and give me the word right before it.

Klendathu

Upvotes: 1

Views: 3627

Answers (1)

Sam
Sam

Reputation: 20486

Take my comment to heart about matching names (not regular) with "regular" expressions.


However, you want to anchor your match to the end of the string with $. I also threw the parenthesis logic into a lookahead, so it doesn't get included in the final match.

\w+(?=\s*\([^)]+\)$)

Demo

Upvotes: 5

Related Questions