1

I am trying to get the first and last name from a column using regex but I'm stumped.

I'm trying:

select
    substring('SMIRTH JR, DAVID ALLEN', '^[^ ,]+') as namemodified

it should return

SMIRTH, DAVID

but it only returns the last name. I can't figure out how to get both.

I also need it to work for:

SMIRTHJR, DAVID ALLEN

since the data isn't very clean. Any ideas?

8
  • The Expected output is 'SMIRTH, DAVID' --oops I'll edit my question. Commented Dec 7, 2017 at 20:45
  • I tested it, but I get 'SMIRTHJR, DAVID ALLEN' not 'SMIRTH, DAVID' Commented Dec 7, 2017 at 20:48
  • Try select regexp_replace('SMIRTH, DAVID ALLEN', '^([^,\s]+?)([JS]R)?\y[^,]*,\s*(\S+\y).*$', '\3, \1') Commented Dec 7, 2017 at 20:57
  • It doesn't filter the name at all still Commented Dec 7, 2017 at 20:58
  • Ok, maybe like here. Commented Dec 7, 2017 at 21:00

1 Answer 1

1

Use regexp_matches function instead of substring (assuming Postgresql 9.x):

select
    regexp_matches(regexp_replace('SMIRTHJR, DAVID ALLEN','(JR|SR),', ','), 
                   '([^\s,]+).*?(, [^\s,]+) [^\s,]+$') as namemodified

The above will return SMIRTH, DAVID for both input strings SMIRTHJR, DAVID ALLEN or SMIRTH JR, DAVID ALLEN

Sign up to request clarification or add additional context in comments.

8 Comments

^[^\s,]+|[^\s,]+$ only returns SMIRTH.
But for I also need it to work for: SMIRTHJR, DAVID ALLEN since the data isn't very clean. requirement, it would have been even easier.
@WiktorStribiżew, while since the data isn't very clean - someone can invent additional cases like SMIRTHJR,DAVIDALLEN - what now?
The data always has a space after the comma so we just have to worry about the JR/SR and spaces. I just wish there was a solution that worked on 5.1.1 - I'm stuck on that old version. :(
Using @WiktorStribiżew 's tool it works, but on my version I get an error saying that it doesn't recognize the function - regexp_matches isn't supported in my version :(
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.