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?
Match everything from the beginning of the string until the first comma:
^(.+?),
?
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
).
How about: yourString.split(",")[0]
^([^,])+
This regexp worked for me in Sublime. It selected everything just before the first comma.
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:
^[^,]*
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.
^[a-zA-Z0-9]+
..use this ... this is the correct answer to get first comma separated value
', BMath, MD'
?