我有一串"单词",如下所示:fIsh mOuntain rIver.单词用空格分隔,我在字符串的开头和结尾添加了空格,以简化"单词"的定义.
我需要更换含有任何的话A,B或C与1含有任何文字X,Y或Z用2,并与所有剩余的词3,如:
the CAT ATE the Xylophone
Run Code Online (Sandbox Code Playgroud)
首先,替换包含A,B或C与1字符串相关的单词变为:
the 1 1 the Xylophone
Run Code Online (Sandbox Code Playgroud)
接下来,替换包含X,Y或Z与2字符串相关的单词变为:
the 1 1 the 2
Run Code Online (Sandbox Code Playgroud)
最后,它替换所有剩余的单词3,例如:
3 1 1 3 2
Run Code Online (Sandbox Code Playgroud)
最终输出是一个只包含数字的字符串,其间有空格.
$5?fish可以是单词.定义单词开头和结尾的唯一特征是空格.ZebrA简单地替换为1.如何用数字替换包含这些特定字符的所有单词,最后用3?替换所有剩余单词?
请尝试以下代码:
function replace(str)
return (str:gsub("%S+", function(word)
if word:match("[ABC]") then return 1 end
if word:match("[XYZ]") then return 2 end
return 3
end))
end
print(replace("the CAT ATE the Xylophone")) --> 3 1 1 3 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1053 次 |
| 最近记录: |