String.find() 包含通配符的单词

String.find() words containing wildcards

我有一些字符串使用通配符“-”而不是 space,而且我很难弄清楚如何处理这些通配符(第一次在lua)

这是我得到的:

string_A = "this-is-a-word"

string_array =
{
    line_A = "this-is-a-word-but-bigger"
    line_B = "this-is-a-bigger-word"
}

for _, string_line in pairs(string_array) do
    if string.find(string_line, string_A) then
    ...
end

每个参数的行为应该像一个单词,这意味着唯一的匹配项是 string_A/line_A,因为它包含相同的块

-是字符串patterns中的魔法字符^$()%.[]*+-?)之一。将它们放在您要查找的字符串中会导致问题。

你有两个选择。

一个

使用 string.find 的可选第四个参数搜索纯字符串。这不会将任何角色视为神奇的。

string.find(string_lineA, stringA, 1, true)

或短

string_lineA:find(stringA, 1, true)

B

使用%

转义任何魔法字符
string.find(string_line, "this%-is%-a%-word")

来自手册:

%x: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any non-alphanumeric character (including all punctuation characters, even the non-magical) can be preceded by a '%' to represent itself in a pattern.

如果我们可以对任何 non-alphanumeric 字符执行此操作,我们就可以通过在任何 non-alphanumeric 字符前面加上 % 来转义任何魔法字符。 %w 匹配字母数字字符。大写字母否定字符 class 所以 %W 是 non-alphanumeric。这导致我们

string.gsub(yourPattern, "%W", "%%%0")

或短

yourPattern:gsub("%W, "%%%0")

其中 %% 是转义后的 %%0 是匹配的字符串。