Lua中含空格/重复字符的字符串匹配失败求助
问题分析与解决方案
你遇到的问题根源在于Lua的string.find默认会把第二个参数当作模式匹配串解析,而非直接匹配普通字符串:
- 你尝试用
%s匹配空格,但如果搜索字符串写为"CH-47%sChinook",实际内容是包含%s两个字符的文本,模式匹配会尝试查找CH-47后紧跟%和s的内容,而非空格,自然匹配不到目标; - 即便你正确使用模式语法,字符串中的
-、()等字符属于模式的特殊符号,未转义时会被错误解析,导致匹配失败。
下面提供两种简单有效的解决方法:
方案一:纯字符串匹配(推荐新手)
给string.find添加第三个参数true,强制函数将第二个参数当作普通字符串处理,无需任何转义或模式语法,直接匹配空格、-等所有字符。
修改后的核心代码片段:
local aName = "CH-47 Chinook" -- 直接写普通空格,不用%s print ("The search string is " .. aName) -- 所有string.find调用都加上第三个参数true if string.find(Interceptor_Types, aName, true) then Num_Interceptors = Num_Interceptors +1 print("TEST Output 3: " .. Num_Interceptors) elseif string.find(CAS_Types, aName, true) then Num_CAS = Num_CAS +1 print("TEST Output 4: " .. Num_CAS) elseif string.find(Helicopter_Types, aName, true) then Num_Helicopters = Num_Helicopters +1 print("TEST Output 5: " .. Num_Helicopters) else Num_Others = Num_Others + 1 end
这种方法完全不需要考虑Lua的模式语法,适合简单的精确匹配场景,省心不易出错。
方案二:正确使用模式匹配
如果需要更灵活的匹配(比如匹配任意空白字符,包括空格、制表符),需遵循Lua模式语法规则:
- 用
%s匹配任意空白字符; - 模式中的特殊字符(
-、(、)、.等)需用%转义,写成%-、%(、%)、%.。
比如匹配CH-47 Chinook的模式串应为"CH%-47%sChinook",匹配Ka-50 III的模式串为"Ka%-50%sIII"。
修改后的测试代码示例:
local aName = "CH%-47%sChinook" -- 转义-,用%s匹配空格 print ("The search string is " .. aName) if string.find(Interceptor_Types, aName) then -- 后续逻辑不变 end
内容的提问来源于stack exchange,提问作者Nathan C.
相关产品推荐
相关产品推荐

