AGH_TORN
AGH_TORN

Reputation: 833

Regex matching names in pattern

I've got a simple pattern LASTNAME, FIRSTNAME MI_IDNUMBER that I've matched with ^[a-zA-Z0-9, ]+_[a-zA-Z0-9]+. The problem I'm running into now are records where the person has a last name with a hyphen like WALKER-REYES, ANNA T_AW12345. I've tried incorporating something like (?=\S*['-])([a-zA-Z'-]+) into it but this only identifies that LASTNAME in the string. What's the best way to string this all together? Not all names will have hyphens.

Upvotes: 0

Views: 47

Answers (1)

Nicolas
Nicolas

Reputation: 8670

The way you built your regex is not optimal. You are matching every character, including space, until you find an underscore ( _ ) and then match the rest. Rather than doing that, you shouldn't match spaces and have every part of your string in different groups.

You can try using this regex, which support hyphens.

^(?: ?([a-zA-Z0-9\-]+),?){2} ([a-zA-Z0-9_]+)

Regular expression visualization

You can test more cases at this regex101

Upvotes: 2

Related Questions