thiebo
thiebo

Reputation: 1435

gsub remove everything before the first comma

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".

Upvotes: 7

Views: 6966

Answers (3)

Sagar Pandya
Sagar Pandya

Reputation: 9498

You can use a positive lookbehind for the first comma then something like this with [] notation:

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

Upvotes: 1

ndnenkov
ndnenkov

Reputation: 36110

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"

Upvotes: 8

sawa
sawa

Reputation: 168209

auteur.partition(",").last
# => " Baudouin, Jacques, Thierry"

Upvotes: 11

Related Questions