tags:

views:

60

answers:

4

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?

+1  A: 

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

JoshD
But if he does `/.*?(?=,)?/`, wouldn't that match the empty string?
LarsH
@LarsH: You're right! I've updated the answer...
JoshD
+5  A: 

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

/^[^,]+/
pbaumann
+1 for a simple solution.
steinar
I had a similar idea. I think you need the parens for the capture, but I may steal your start-of-line anchor.
Telemachus
A good idea! +1
LarsH
@Telemachus, you don't need parens in order for the whole regexp to match the required string.
LarsH
@Telemachus, depends on how you use it, e.g.: string.match(/.../) would return anything that matches the regex or nil if nothing matched, no capture needed. EDIT: What LarsH said.
pbaumann
@LarsH Maybe I'm confused, but without the parens, `$1` is not set (whether the regex matches the whole string or a sub-string).
Telemachus
@pbaumann Fair enough - I see now that he wasn't necessarily using `=~`.
Telemachus
+2  A: 

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

/([^,]+)/
Telemachus
That's nice. It works just as /[^,]+/
brad
+3  A: 

Does it have to be a regex? Another solution:

text.split(',').first
Mark Thomas
@Mark - but you could just use the string `.split(',')`. Probably no difference in a case like this.
Telemachus
It doesn't have to be - but I 'want' it to be
brad
Curious. Why do you 'want' it to be a regex? Is there an advantage?
Scott Radcliff
@brad For what it's worth, you shouldn't get into the habit of thinking that all string problems require regexes. You can handle lots of cases in other ways.
Telemachus
I'd use `'text'.split(',').first` which avoids a regex entirely. :-)
Greg
@Telemachus and @Greg, I've updated my response, changing `/,/` to `','`.
Mark Thomas