ruby - 带有字符串操作的 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")
非常感谢任何有助于实现预期的帮助
解决方案
这将起作用:
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?不同的库有不同的优势。
推荐阅读
- azure - 当持久性卷声明超过存储时会发生什么?
- flutter - 如何使卡片像颤动的标签一样可滑动?
- extjs - 基于 extjs 网格中的另一个组合框填充字段
- swift - 快速获取日期范围内的日期名称和日期重复次数
- android - 将基于 Web 的数据库管理应用程序转换为移动应用程序以使其离线工作
- arduino - 如何从 Arduino“9 Axis Motion Shield”获取数据和校准
- laravel - 如何在 laravel 中使用相同的表单进行添加和编辑
- .net-core - 编译和使用自定义 Dotnet/CoreFx
- ruby-on-rails - Active Record:未在嵌套关系中分配 User_id
- jquery - 单击添加新行按钮第一行单选按钮值在 jquery 中未定义