55

I want to extract text before first comma (first and last name) from strings like:

John Smith, RN, BSN, MS
Thom Nev, MD
Foo Bar, MD,RN

I tried with regex:

(.*)\s(.*),\s

but this doesn't work for all situations. How to achieve this?

2

6 Answers 6

127

Match everything from the beginning of the string until the first comma:

^(.+?),
3
  • 4
    I understand that ^ means at beginning, .+ means one or zero of any character, but don't know what is purpose of ?. Aug 27, 2012 at 20:25
  • 13
    @ИванБишевац, ? in this context means non-greedy. Basically it means that the expression should match everything until it encounters the first ,. Without ?, it would look for everything until the last ,. Also, .+ means "one or more of any character", not "one or zero". "One or zero" is ? following an atom (for example ab?c would match abc or ac).
    – rid
    Aug 27, 2012 at 20:38
  • 12
    This includes comma itself (at least when I tried that in Sublime). The following option worked for me: ^([^,])+
    – AlexHalkin
    Apr 17, 2018 at 23:53
38

How about: yourString.split(",")[0]

3
  • 2
    I accepted answer with regex since I asked for it and want to learn regex. Anyway great answer. +1 from me. Aug 27, 2012 at 20:23
  • Note: Found this answer Googling for syntax, and had it start throwing the error "invalid byte sequence in US-ASCII" - turns out there's some unicode character hiding in there, for anyone else who tries to copy/paste (spli\U+FFC2\U+FFADt(",")[0]). Oct 20, 2013 at 23:22
  • 2
    It also can be yourString.split(',').first Apr 14, 2014 at 2:17
24
^([^,])+

This regexp worked for me in Sublime. It selected everything just before the first comma.

1
  • 2
    This should be the accepted answer. The OP asked for everything before the comma and the accepted answer includes the comma.
    – mikey
    Oct 21, 2022 at 12:18
13

How about the following:

[^,]*

[^,]* means "match any number of characters that are not commas", which I think it exactly what you are trying to do here. You may want to anchor it to the beginning of the string iwth ^, like this:

^[^,]*
6

You have to use non greedy regex operators, try: (.+?), instead of: (.+),. Note that when using greedy operators, you'll match everything before the last comma instead of the first.

-4
^[a-zA-Z0-9]+ 

..use this ... this is the correct answer to get first comma separated value

1
  • 1
    One simple special letter and it's broken.
    – Puce
    Sep 29, 2015 at 13:50

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.