如何读取字符串的特定部分?

How to read a specific part of a string?

本质上,我需要的是读取字符串的某个部分。

示例:

我有一个包含“12 31”的字符串。 但是,我需要将这些数字放入单独的变量中。只需将 12 排序为变量 A,将 31 排序为变量 B。

我该怎么办?

您可以使用 Lua Patterns:

> ExampleString = "12 31"
> ExampleString:match("(%d+)%s+(%d+)")
12      31
> SubString1, SubString2= ExampleString:match("(%d+)%s+(%d+)")
> Number1 = tonumber(SubString1)
> Number2 = tonumber(SubString2)

Pattern expression看似复杂,其实很简单。 ()之间的东西命名为captures,找到就会返回。在这里,我们想要 2 个结果,所以我们有 2 对 ()%d+ 表示我们要查找至少包含 1 个数字 (+) 的字符串。

2个数之间相隔一些space个%s+,至少1个(+).

综上所述,我们要提取 (Number1)space(Number2)

函数string.match is used to match against the given pattern and returns the found strings. The last step is to use the function tonumber将找到的子字符串转换为Lua个数字。