willdanceforfun
willdanceforfun

Reputation: 11240

Match both of these with regex, not just one of

I'm looking in a sql table through a bunch of names and I want to get a list of all the different titles used. e.g. SNR, MRS, MR, JNR etc

Sometimes there is an entry that might have 2 titles, e.g: MR NAME NAME JNR. I want both of these titles 'MR' & 'JNR'

I thought a good way to do this would be with regex and find any names that have 2 or 3 characters. A title at the front would be followed by a space, while a title at the end would be preceded by one. So I have:

/(^[A-Z]{2,3})\s|\s(^[A-Z]{2,3}$)/

a regex101 example here.

As you can see I've used 'match either A or B' thing. If I throw at it a name with a title at either the start or finish, I end up getting what I want, but I don't know how to tell it to get both. i.e. strings with 2 titles will only give me back one match.

How do I get both?

Upvotes: 0

Views: 66

Answers (1)

Whothehellisthat
Whothehellisthat

Reputation: 2152

Instead of an "OR", you could just match any character in between:

(^[A-Z]{3})\s.*\s([A-Z]{3}$)

Upvotes: 1

Related Questions