[英]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"))
在此示例中,程序將嘗試匹配不以h或e或l或o字符開頭且旁邊有空格和世界的字符串的任何部分。 但是我想做一個類似這樣的詞集,可以匹配整個詞,並找到字符串中不是以詞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
: 來自hola
的l
與來自hello
的第二個l
是相同的 position 要查找前面沒有hello
的world
,我會結合對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`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.