Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gsub remove everything before the first comma

Tags:

regex

ruby

gsub

I have this string:

auteur = "comte de Flandre et Hainaut, Baudouin, Jacques, Thierry"

I want to remove everything before the first comma i.e. in this case keep "Baudouin, Jacques, Thierry"

Tried this :

nom = auteur.gsub(/.*,/, '')

But that removes every before the last comma and keeps only "Thierry".

like image 551
thiebo Avatar asked Jan 20 '17 13:01

thiebo


2 Answers

auteur.partition(",").last
# => " Baudouin, Jacques, Thierry"
like image 80
sawa Avatar answered Sep 22 '22 02:09

sawa


Use #sub instead of #gsub to remove only the first occurrence and make the repetition lazy (?):

auteur = "comte de Flandre et Hainaut, Baudouin, Jacques, Thierry"
nom = auteur.sub(/.*?,/, '') # => " Baudouin, Jacques, Thierry"

Or don't use regexes at all (returns the original string if no commas are present):

auteur.split(',', 2).last # => " Baudouin, Jacques, Thierry"
like image 28
ndnenkov Avatar answered Sep 23 '22 02:09

ndnenkov