【发布时间】:2018-06-30 18:00:25
【问题描述】:
我没有在https://ruby-doc.org/core-2.5.0/Regexp.html 中找到提到\K,但它似乎已实现(Support of \K in regex) - 我拥有的版本是2.5.0p0
但是,对于此示例,它没有按我的预期工作(基于 perl 的行为):
$ # expected behavior, replace empty fields with NA where comma is separator
$ echo ',a,,,b,' | ruby -pe 'gsub(/(?<=^|,)(?=,|$)/, "NA")'
NA,a,NA,NA,b,NA
$ # why a,,,b is not changing to a,NA,NA,b here?
$ echo ',a,,,b,' | ruby -pe 'gsub(/(^|,)\K(?=,|$)/, "NA")'
NA,a,NA,,b,NA
$ # reference from perl, where ^|, is considered as variable length
$ echo ',a,,,b,' | perl -pe 's/(^|,)\K(?=,|$)/NA/g'
NA,a,NA,NA,b,NA
$ echo ',a,,,b,' | perl -pe 's/(?<=^|,)(?=,|$)/NA/g'
Variable length lookbehind not implemented in regex m/(?<=^|,)(?=,|$)/ at -e line 1
注意:我特别想了解\K 和ruby 中的外观,而不是寻找解决此问题的其他方法,例如:
$ echo ',a,,,b,' | ruby -lne 'print $_.split(",",-1).map { |s| s=="" ? "NA" : s }.join","'
NA,a,NA,NA,b,NA
【问题讨论】:
标签: ruby regex regex-lookarounds