brad
brad

Reputation: 9773

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

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?

Upvotes: 14

Views: 51688

Answers (4)

Mark Thomas
Mark Thomas

Reputation: 37517

Does it have to be a regex? Another solution:

text.split(',').first

Upvotes: 15

Telemachus
Telemachus

Reputation: 19715

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

/([^,]+)/

Upvotes: 25

JoshD
JoshD

Reputation: 12814

How about /.*?(?=,|$)/ That way it either reads to the end or to a comma.

Upvotes: 2

pbaumann
pbaumann

Reputation: 627

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

/^[^,]+/

Upvotes: 12

Related Questions