Gsub removes everything up to the first comma

I have this line:

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

I want to delete everything before the first comma, that is, in this case, save "Baudouin, Jacques, Thierry"

Tried this:

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

But this removes each before the last comma and only retains the Thierry.

+4
source share
3 answers
auteur.partition(",").last
# => " Baudouin, Jacques, Thierry"
+8
source

Use #subinstead #gsubto 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 do not use regular expressions at all (returns the original string if there is no comma):

auteur.split(',', 2).last # => " Baudouin, Jacques, Thierry"
+5
source

lookbehind , - []:

nom = auteur[/(?<=\,\s).*/]
#=> "Baudouin, Jacques, Thierry"
+1

Source: https://habr.com/ru/post/1667369/


All Articles