首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Lua string.match..。在单词上进行匹配,结尾是可选的标点符号。

Lua string.match..。在单词上进行匹配,结尾是可选的标点符号。
EN

Stack Overflow用户
提问于 2014-07-19 01:34:07
回答 1查看 943关注 0票数 2

好吧,我对Lua语言很陌生。

我正在尝试遍历一些字符串匹配,但是如果在我的句子“字典”中的单词后面有任何标点符号,那么匹配就无效了。

我原以为在“零标点符号或一个标点符号”上添加一个%p?是匹配的,但情况似乎并非如此?

代码语言:javascript
代码运行次数:0
运行
复制
local string_that_matches = string.match(Dictionary[i], textsubmitted..'%p?')

编辑:添加更多信息。下面是完整的例程:

嗯..。我只是想看看string_that_matches是不是零..。如果不是,那么将它添加到一个新的匹配数组中,因为我们在这里循环了大约50个条目:

代码语言:javascript
代码运行次数:0
运行
复制
local dictSize = table.maxn(Dictionary)
matches = {} -- new array to hold matches

for i=1,dictSize do -- Loop through dictionary items
    local string_that_matches = string.match(Dictionary[i],textsubmitted..'%p?')
    if string_that_matches ~= nil then
        table.insert(matches, Dictionary[i]) 
    end
end
return matches   
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-19 01:55:49

所有这些组合都符合我的预期:

代码语言:javascript
代码运行次数:0
运行
复制
string.match("Good night, boys and girls.", "night")

返回night

代码语言:javascript
代码运行次数:0
运行
复制
string.match("Good night, boys and girls.", "night%p?")

返回night,

如果您希望匹配不包括(可选的)标点符号,那么将您的textsubmitted包到括号中:

代码语言:javascript
代码运行次数:0
运行
复制
string.match("Good night, boys and girls.", "(night)%p?")

这将返回night

下面是一个您可以尝试的完整示例:

代码语言:javascript
代码运行次数:0
运行
复制
local Dictionary = {"Good night, boys and girls."}

function trymatch(textsubmitted)
  local dictSize = table.maxn(Dictionary)
  matches = {} -- new array to hold matches

  for i=1,dictSize do -- Loop through dictionary items
    local string_that_matches = string.match(Dictionary[i],textsubmitted..'%p?')
    if string_that_matches ~= nil then
      table.insert(matches, Dictionary[i]) 
    end
  end
  return matches
end

print(trymatch("Good")[1])
print(trymatch("night")[1])
print(trymatch("boys")[1])
print(trymatch("nothing")[1])

这是预期的印刷品:

代码语言:javascript
代码运行次数:0
运行
复制
Good night, boys and girls.
Good night, boys and girls.
Good night, boys and girls.
nil
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24835919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档