首页 > 解决方案 > 带有字符串操作的 Ruby gsub

问题描述

我是 ruby​​ 新手并编写表达式以通过散列其中的值来替换 xml 标记之间的字符串。

我做了以下替换为新密码

puts "<password>check1</password>".gsub(/(?<=password\>)[^\/]+(?=\<\/password)/,'New \0')
RESULT: <password>New check1</password> (EXPECTED)

我的期望是得到这样的结果(值“New check1”的 Md5 校验和)

<password>6aaf125b14c97b307c85fc6e681c410e</password>

我通过以下方式进行了尝试,但都没有成功(我已经包含了所需的库“require 'digest'”)。

puts "<password>check1</password>".gsub(/(?<=password\>)[^\/]+(?=\<\/password)/,Digest::MD5.hexdigest('\0'))
puts "<password>check1</password>".gsub(/(?<=password\>)[^\/]+(?=\<\/password)/,Digest::MD5.hexdigest '\0')
puts "<password>check1</password>".gsub(/(?<=password\>)[^\/]+(?=\<\/password)/, "Digest::MD5.hexdigest \0")

非常感谢任何有助于实现预期的帮助

标签: rubyregexstringreplace

解决方案


这将起作用:

require 'digest'

line = "<other>stuff</other><password>check1</password><more>more</more>"

line.sub(/<password>(?<pwd>[^<]+)<\/password>/, Digest::SHA2.hexdigest(pwd))

 => "<other>stuff</other>8a859fd2a56cc37285bc3e307ef0d9fc1d2ec054ea3c7d0ec0ff547cbfacf8dd<more>more</more>"

确保输入一次是一行,你可能想要sub,而不是gsub

PS:同意 Tom Lord 的评论。如果您的 XML 大小不庞大,请尝试使用 XML 库来解析它……也许是 Ox 或 Nokogiri?不同的库有不同的优势。


推荐阅读