【问题标题】:Patterns in Lua with spaceLua 中带空格的模式
【发布时间】:2014-07-04 15:39:51
【问题描述】:

我如何使用string.gmatch(text, pattern) 来做到这一点:

text = "Hello.%23 Awesome7^.."
pattern = --what to put here?
for word in string.gmatch(text, pattern) do
  print(word)
end
--Result
>test
Hello.%23
Awesome7^..
>

我一直在使用"%w+%p",但这会导致:

>test
Hello.
%
23
Awesome7^
.
.

这不是我们想要的结果。

注意:我没有测试过这个确切的字符串,它可能会有所不同......但仍然不会产生所需的结果

【问题讨论】:

    标签: string lua lua-patterns


    【解决方案1】:

    从你的例子来看,每个单词都不包含空格,并且用空格分隔,所以最简单的模式是"%S+"

    text = "Hello.%23 Awesome7^.."
    pattern = "%S+"
    for word in string.gmatch(text, pattern) do
      print(word)
    end
    

    "%s" 匹配空格字符,"%S" 匹配非空格字符。

    【讨论】:

    • 这不会导致 gmatch 打印“”吗?编辑:nvm,我不知道大写字母做了不同的事情
    • @KingofGamesYami 测试一下,注意是大写"%S+"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2012-06-13
    • 2021-06-07
    • 1970-01-01
    • 2018-02-05
    • 2021-10-16
    相关资源
    最近更新 更多