Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match a string up to the first comma (if present) with a Ruby regexp

Tags:

regex

ruby

I'm struggling to get a regexp (in Ruby) that will provide the following

"one, two" -> "one"
"one, two, three" -> "one"
"one two three" -> "one two three"

I want to match any characters up until the first comma in a string. If there are no commas I want the entire string to be matched. My best effort so far is

/.*(?=,)?/

This produces the following output from the above examples

"one, two" -> "one"
"one, two, three" -> "one, two"
"one two three" -> "one two three"

Close but no cigar. Can anyone help?

like image 268
brad Avatar asked Oct 27 '10 00:10

brad


2 Answers

I'm wondering if it can't be simpler:

/([^,]+)/
like image 116
Telemachus Avatar answered Oct 05 '22 06:10

Telemachus


Would matching only non commas from the beginning work? e.g.:

/^[^,]+/
like image 43
pbaumann Avatar answered Oct 05 '22 07:10

pbaumann