使用正则表达式根据用户名的最终字母更改文本 [英] Changing text based on the final letter of user name using regular expression

查看:60
本文介绍了使用正则表达式根据用户名的最终字母更改文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to change the ending of the user name based on the use case (in the language system will operate, names ends depending on how it is used).

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

So need to define all endings of names and define the replacement for them. Was suggested to use .gsub regular expression to search and replace in a string:

根据用户的最终字母更改文本名称

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

这将用ai替换e,所以姓氏= namai surnamai".

this will replace e with ai, so "name surname = namai surnamai".

如何在同一记录中将其用于更多选项,例如:"e = ai,us = mi,i = as"?

How can it be used for more options like: "e = ai, us = mi, i = as" on the same record?

谢谢

推荐答案

您可以将String#gsub与block一起使用. 文档说:

You can use String#gsub with block. Docs say:

以块形式,将当前的匹配字符串作为参数传递,并且将适当设置变量,例如$ 1,$ 2,$`,$&和$'.该块返回的值将替换为每次调用时的匹配项.

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.

因此,您可以将正则表达式与要替换的所有子字符串串联使用,然后在块中替换它,例如使用将匹配项映射到替换项的哈希值.

So you can use a regex with concatenation of all substrings to be replaced and then replace it in the block, e.g. using a hash that maps matches to replacements.

完整示例:

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

这篇关于使用正则表达式根据用户名的最终字母更改文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆