基于数字字母组合的Lua字符串格式化:荷兰车牌实现问询
荷兰车牌格式化的Lua实现方案
完全可行,用Lua的字符串模式匹配就能搞定这五种格式的检测和格式化,逻辑简单直接,适合新手上手。
实现思路
- 先统一输入格式:去掉输入中可能存在的横杠,同时把字母转成大写,避免大小写和已有分隔符干扰匹配
- 针对你列出的5种格式,分别编写对应的匹配模式,依次尝试匹配输入字符串
- 只要匹配上某一种格式,就替换成带横杠的目标格式;如果都没匹配到,返回原字符串或自定义提示
完整代码实现
function formatDutchLicensePlate(plate) -- 预处理:移除横杠,字母转大写 local cleanPlate = plate:gsub("%-", ""):upper() -- 匹配格式1: 99-XX-XX local formatted = cleanPlate:gsub("^(%d%d)(%a%a)(%a%a)$", "%1-%2-%3") if formatted ~= cleanPlate then return formatted end -- 匹配格式2: 99-XXX-9 formatted = cleanPlate:gsub("^(%d%d)(%a%a%a)(%d)$", "%1-%2-%3") if formatted ~= cleanPlate then return formatted end -- 匹配格式3: 9-XXX-99 formatted = cleanPlate:gsub("^(%d)(%a%a%a)(%d%d)$", "%1-%2-%3") if formatted ~= cleanPlate then return formatted end -- 匹配格式4: XX-999-X formatted = cleanPlate:gsub("^(%a%a)(%d%d%d)(%a)$", "%1-%2-%3") if formatted ~= cleanPlate then return formatted end -- 匹配格式5: X-999-XX formatted = cleanPlate:gsub("^(%a)(%d%d%d)(%a%a)$", "%1-%2-%3") if formatted ~= cleanPlate then return formatted end -- 所有格式都不匹配时返回提示 return "无法识别的车牌格式: " .. plate end -- 测试示例 print(formatDutchLicensePlate("91FKTG")) -- 输出: 91-FK-TG print(formatDutchLicensePlate("GB000T")) -- 输出: GB-000-T print(formatDutchLicensePlate("1ABC23")) -- 输出: 1-ABC-23 print(formatDutchLicensePlate("99XYZ9")) -- 输出: 99-XYZ-9 print(formatDutchLicensePlate("x123yz")) -- 输出: X-123-YZ(自动转大写) print(formatDutchLicensePlate("AB-123-C")) -- 输出: AB-123-C(兼容带横杠的输入)
代码说明
^和$用来确保匹配整个字符串,避免部分匹配的情况%d匹配数字,%a匹配字母,括号()用来捕获匹配的片段,替换时用%1、%2、%3对应捕获的内容- 每次用
gsub尝试替换后,判断结果是否和原字符串不同,以此确认是否匹配成功
内容的提问来源于stack exchange,提问作者Avanae
相关产品推荐
相关产品推荐

