Иван Бишевац
Иван Бишевац

Reputation: 14671

Extract text before first comma with regex

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?

Upvotes: 57

Views: 184563

Answers (6)

AlexHalkin
AlexHalkin

Reputation: 1127

^([^,])+

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

Upvotes: 28

aquinas
aquinas

Reputation: 23796

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

Upvotes: 38

nagina
nagina

Reputation: 1

^[a-zA-Z0-9]+ 

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

Upvotes: -5

danielrvt
danielrvt

Reputation: 10926

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.

Upvotes: 6

rid
rid

Reputation: 63540

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

^(.+?),

Upvotes: 131

Andrew Clark
Andrew Clark

Reputation: 208565

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:

^[^,]*

Upvotes: 13

Related Questions