Regex negative lookbehind in Ruby doesn't seem to work
Asked Answered
C

1

6

Making an argument parser. I want to split a string into an array where the delimiter is ", " except when preceded by "|". That means string

"foo, ba|, r, arg"

should result in

`["foo", "ba|, r", "arg"]`

I'm trying to use this regex: (?<!\|), which works in http://regexhero.net/tester/ but when I try

args.split(/(?<!\|), /)

in ruby, I get an error: undefined (?...) sequence: /(?<!\|), /

Chavez answered 30/9, 2011 at 3:18 Comment(3)
This works in 1.9 so if you can upgrade your Ruby installation, go ahead and do so.Huntingdonshire
@Michael Kohl that's exactly what I did :)Chavez
Also, for Ruby regex testing, I'd use Rubular.Torquay
M
10

Ruby's regex engine doesn't support lookbehind (yet).

You'd need to switch to 1.9 or use Oniguruma.


If that's not an option, you can search for |, and replace it with some sort of marker. After all is said and done, put the |, back.

You can also try a regex like:

/(?:[^|]), /

But obviously the (?:[^|]) is not zero-width, which means you'll need to do some extra work afterwards.

Moravia answered 30/9, 2011 at 3:22 Comment(1)
note that Ruby now supports negative lookbehind at least as of 1.9.3: ruby-doc.org/core-1.9.3/Regexp.htmlDruse

© 2022 - 2024 — McMap. All rights reserved.