我正在尝试解析(在Ruby语言中)有效的UNIX passwd文件格式:逗号分隔符,并使用转义字符\,这样任何转义的内容都应该被视为字面意思。我正在尝试使用正则表达式来实现这一点,但我做得不够--即使在使用Oniguruma进行前视/后视断言时也是如此。
从本质上讲,以下所有操作都应该有效:
a,b,c # => ["a", "b", "c"]
\a,b\,c # => ["a", "b,c"]
a,b,c\
d # => ["a", "b", "c\nd"]
a,b\\\,c # => ["a", "b\,c"]有什么想法吗?
第一个反应看起来相当不错。使用包含以下内容的文件
\a,,b\\\,c\,d,e\\f,\\,\
g它提供了:
[["\\a,"], [","], ["b\\\\\\,c\\,d,"], ["e\\\\f,"], ["\\\\,"], ["\\\ng\n"], [""]]很接近了。我不需要在第一次传递时做取消转义,只要一切都在逗号上正确拆分即可。我尝试了Oniguruma,最后得到了(更长的):
Oniguruma::ORegexp.new(%{
(?: # - begins with (but doesn't capture)
(?<=\A) # - start of line
| # - (or)
(?<=,) # - a comma
)
(?: # - contains (but doesn't capture)
.*? # - any set of characters
[^\\\\]? # - not ending in a slash
(\\\\\\\\)* # - followed by an even number of slashes
)*?
(?: # - ends with (but doesn't capture)
(?=\Z) # - end of line
| # - (or)
(?=,)) # - a comma
},
'mx'
).scan(s)发布于 2010-02-13 05:01:32
试试这个:
s.scan(/((?:\\.|[^,])*,?)/m)它不会翻译\后面的字符,但这可以在以后作为一个单独的步骤完成。
发布于 2010-02-13 04:53:18
我想尝试一下CSV类。
和正则表达式解决方案(hack?)可能如下所示:
#!/usr/bin/ruby -w
# contents of test.csv:
# a,b,c
# \a,b\,c
# a,b,c\
# d
# a,b\\\,c
file = File.new("test.csv", "r")
tokens = file.read.scan(/(?:\\.|[^,\r\n])*|\r?\n/m)
puts "-----------"
tokens.length.times do |i|
if tokens[i] == "\n" or tokens[i] == "\r\n"
puts "-----------"
else
puts ">" + tokens[i] + "<"
end
end
file.close它将产生输出:
-----------
>a<
>b<
>c<
-----------
>\a<
>b\,c<
-----------
>a<
>b<
>c\
d<
-----------
>a<
>b\\\,c<
-----------https://stackoverflow.com/questions/2255031
复制相似问题