Ruby 正则替换求助

Peter · 2016年01月08日 · 最后由 saiga 回复于 2016年01月08日 · 2263 次阅读

我要把这个字符串

{{foobar bar
$aa bb=cc dd
$ee,ff=gg hh
$iiü jj=kk ll
}}

替换成:

{{foobar bar
$aa_bb=cc dd
$ee_ff=gg hh
$iiü_jj=kk ll
}}

目的是在 aa bb, ee,ffiiü jj 之间添加下划线, 也就是在 $= 之间的字符除字母 ( ä,ö,ü,ß 等算有效字母) 外都要换成下划线。 基本功不行,google 到的也是一些简单的例子,希望高手相助,谢谢!

不高明解法一个

str1 = str.each_line.map do |line|
  line.sub(/(?<=\$)(.*)(?==)/) do |match|
    match.split.join('_')
  end
end
p str1

试一个

str.gsub(/(?<=^\$)(\p{Word}+)(?:\s*,\s*|\s+)(\p{Word}+)(?=\s*\=)/, '\1_\2')

#1 楼 @nowherekai #2 楼 @saiga 谢谢两位,学到了

http://ruby-doc.org/core-2.1.1/Regexp.html

(?=pat) - Positive lookahead assertion: ensures that the following characters match pat, but doesn't include those characters in the matched text

(?<=pat) - Positive lookbehind assertion: ensures that the preceding characters match pat, but doesn't include those characters in the matched text

The (?:…) construct provides grouping without capturing. That is, it combines the terms it contains into an atomic whole without creating a backreference.

需要 登录 后方可回复, 如果你还没有账号请 注册新账号