Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract text before first comma with regex

Tags:

regex

ruby

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?

like image 322
Иван Бишевац Avatar asked Aug 27 '12 20:08

Иван Бишевац


People also ask

How do you extract the text before the first comma?

Select a blank cell, and type this formula =LEFT(A1,(FIND(" ",A1,1)-1)) (A1 is the first cell of the list you want to extract text) , and press Enter button. Tips: (1) If you want to extract text before or after comma, you can change " " to ",".

How do you match a comma in regex?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.


2 Answers

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

^(.+?), 
like image 172
rid Avatar answered Sep 21 '22 03:09

rid


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

like image 26
aquinas Avatar answered Sep 19 '22 03:09

aquinas