gpt4 book ai didi

ruby-on-rails - 使用正则表达式根据用户名的最后一个字母更改文本

转载 作者:数据小太阳 更新时间:2023-10-29 07:54:47 25 4
gpt4 key购买 nike

我希望根据用例更改用户名的结尾(在语言系统中将运行,名称结尾取决于它的使用方式)。

因此需要定义名称的所有结尾并定义它们的替换。建议使用 .gsub 正则表达式在字符串中搜索和替换:

Changing text based on the final letter of user name

"name surname".gsub(/e\b/, 'ai')

这会将 e 替换为 ai,因此“name surname = namai surnamai”。

如何在同一记录上使用更多选项,例如:“e = ai, us = mi, i = as”?

谢谢

最佳答案

您可以将 String#gsub 与 block 一起使用。 Docs说:

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

因此您可以使用正则表达式连接所有要替换的子字符串,然后在 block 中替换它,例如使用将匹配映射到替换的哈希。

完整示例:

replacements = {'e'=>'ai', 'us'=>'mi', 'i' => 'as'}
['surname', 'surnamus', 'surnami'].map do |s|
s.gsub(/(e|us|i)$/){|p| replacements[p] }
end

关于ruby-on-rails - 使用正则表达式根据用户名的最后一个字母更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53633649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com