How can I match a space without a leading comma?
My use case is I would like to split a string on space without a leading comma e.g. "id 10, 11"
How can I match a space without a leading comma?
My use case is I would like to split a string on space without a leading comma e.g. "id 10, 11"
No need for a regex, just split twice:
"id 10, 11".split(",").first.split #=> ["id", "10"]
You could use the regular expression
r = /(?<!,) /
which reads, "match one space not preceded by a space" ((?!,)
being a negative lookbehind).
"fe, fi, fo and fum".split r
#=> ["fe, fi, fo", "and", "fum"]
"fe, fi, fo\nand fum".split r
#=> ["fe, fi, ", "", "", "", "fo\nand", "fum"]
If one wishes to break on one or more spaces not preceded by a comma, use
r = /(?<!,) +/
"fe, fi, fo\nand fum".split r
#=> ["fe, fi, ", "fo\nand", "fum"]
To split on one or more whitespace characters not preceded by a comma, use
r = /(?<!,)\s+/
"fe, fi, fo\nand fum".split r
#=> ["fe, fi, ", "fo", "and", "fum"]
It may prudent to first perform String#lstrip.
r = /(?<!,)\s+/
" fe, fi, fo\nand fum ".split r
#=> ["", "fe, fi, ", "fo", "and", "fum"]
" fe, fi, fo\nand fum ".lstrip.split r
#=> ["fe, fi, ", "fo", "and", "fum"]
Depending on requirements, one could instead take @elyvn's advice and write
r = /(?<=[^,])\s+/
which reads, "match one or more whitespace characters preceded by a character other than a comma" ((?<=[^,])
being positive lookbehind).
" fe, fi, fo\nand fum ".split r
#=> [" fe, fi, ", "fo", "and", "fum"]