如何在Lua中查找和替换包含特定字符的单词?

Vil*_*age 2 lua

我有一串"单词",如下所示:fIsh mOuntain rIver.单词用空格分隔,我在字符串的开头和结尾添加了空格,以简化"单词"的定义.

我需要更换含有任何的话A,BC1含有任何文字X,YZ2,并与所有剩余的词3,如:

 the CAT ATE the Xylophone
Run Code Online (Sandbox Code Playgroud)

首先,替换包含A,BC1字符串相关的单词变为:

 the 1 1 the Xylophone
Run Code Online (Sandbox Code Playgroud)

接下来,替换包含X,YZ2字符串相关的单词变为:

 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.
  • 该字符串为UTF-8.

如何用数字替换包含这些特定字符的所有单词,最后用3?替换所有剩余单词?

pra*_*pin 7

请尝试以下代码:

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)