簡體   English   中英

如何在 Lua 模式匹配中創建詞集/類?

[英]How to create a word set/class in Lua pattern matching?

我正在嘗試在 Lua 中創建一個詞集(類)而不是字符集(類)。

例如:

local text = "hello world, hi world, hola world"
print(string.find(text, "[^hello] world"))

在此示例中,程序將嘗試匹配不以helo字符開頭且旁邊有空格和世界的字符串的任何部分。 但是我想做一個類似這樣的詞集,可以匹配整個詞,並找到字符串中不是以詞hello開頭的部分,並且旁邊有空格和世界

我試過的:

local text = "hello world, hi world, hola world"
print(string.find(text, "[^h][^e][^l][^l][^o] world"))

由於某種原因它沒有工作。

我正在嘗試在 Lua 中創建一個詞集(類)而不是字符集(類)。

這在一般情況下是不可能的。 Lua 模式在字符級別運行:量詞只能應用於字符或字符集(以及一些特殊的模式項),但不存在交替,沒有“子表達式”等。模式不具備為此所需的表達能力。

local text = "hello world, hi world, hola world"
print(string.find(text, "[^h][^e][^l][^l][^o] world"))

此模式轉換為:“查找前面有空格和 5 個字符的world ,其中每個字符可能不是 hello world 的相應字符。這意味着以下所有內容都不匹配:

  • hi world : world之前只有三個字符
  • hxxxx world : 第一個字符與hello的第一個字符相同
  • ... hola world : 來自holal與來自hello的第二個l是相同的 position

要查找前面沒有helloworld ,我會結合對string.find的多次調用來搜索字符串,始終尋找前面的hello

-- str: Subject string to search
-- needle: String to search for
-- disallowed_prefix: String that may not immediately precede the needle
-- plain: Disable pattern matching
-- init: Start at a certain position
local function string_find_prefix(str, needle, disallowed_prefix, plain, init)
    local needle_start, needle_end = str:find(needle, init or 1, plain)
    if not needle_start then return end -- needle not found
    local _, prefix_end = str:find(disallowed_prefix, init or 1, plain)
    -- needle may not be prefixed with the disallowed prefix
    if (not prefix_end) or needle_start > prefix_end + 1 then
        -- prefix not found or needle starts after prefix, return match
        return needle_start, needle_end
    end
    return string_find_prefix(str, needle, disallowed_prefix, plain, prefix_end + 2)
end
print(string_find_prefix("hello world, hi world, hola world", "world", "hello ")) -- 17 21: Inclusive indices of the `world` after `hi`

參見string.find (s, pattern [, init [, plain]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM