Regex negative lookbehind in Ruby doesn't seem to work

折月煮酒 提交于 2019-12-01 16:42:37

问题


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: /(?<!\|), /


回答1:


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.



来源:https://stackoverflow.com/questions/7605615/regex-negative-lookbehind-in-ruby-doesnt-seem-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!