Appearance
字符串处理函数
函数列表
1. 将一个二进制字符串转换为以16进制或者10进制显示的字符串 (strutils.bin2Hex)
说明: 将一个二进制字符串转换为以16进制或者10进制显示的字符串
函数: strutils.bin2Hex(data,ishex)
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | 字符串 | 字符串类型 |
| ishex | 布尔 | 如果为true表示16进制显示,否则以10进制显示 |
返回值:
| 返回值类型 | 说明 |
|---|---|
| 字符串 | 字符串类型 |
示例:
lua
local r = strutils.bin2Hex("hello",true)
print(r)2. 字符串分割 (strutils.split)
说明: 字符串分割
函数: strutils.split(str, delimiter, limit)
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
| str | 字符串 | 要分割的字符串 |
| delimiter | 字符串 | 分隔符,默认为空格 |
| limit | 数字 | 可选,最大分割次数 |
返回值:
| 返回值类型 | 说明 |
|---|---|
| table | 返回包含分割后子字符串的表 |
示例:
lua
-- 示例1: 按空格分割
local text = "hello world this is a test"
local words = strutils.split(text)
print("单词分割:")
for i, word in ipairs(words) do
print(i, word)
end
-- 示例2: 按逗号分割
local csv = "apple,banana,orange,grape"
local fruits = strutils.split(csv, ",")
print("\n水果列表:")
for i, fruit in ipairs(fruits) do
print(i, fruit)
end
-- 示例3: 限制分割次数
local path = "usr/local/bin/app"
local parts = strutils.split(path, "/", 2)
print("\n路径分割(限制2次):")
for i, part in ipairs(parts) do
print(i, part)
end
-- 示例4: 多字符分隔符
local data = "name==value||age==25||city==beijing"
local pairs = strutils.split(data, "||")
print("\n键值对分割:")
for i, pair in ipairs(pairs) do
print(i, pair)
end
-- 示例5: 处理空分隔符
local result, err = strutils.split("test", "")
if not result then
print("错误:", err)
end3. 字符串修剪 (strutils.trim)
说明: 字符串修剪
函数: strutils.trim(str,chars)
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
| str | 字符串 | 要修剪的字符串 |
| chars | 字符串 | 可选,要修剪的字符集合,默认为空白字符 |
返回值:
| 返回值类型 | 说明 |
|---|---|
| 字符串 | 返回修剪后的字符串 |
示例:
lua
-- 示例1: 修剪空白字符
local text1 = " hello world "
local trimmed1 = strutils.trim(text1)
print("修剪前后:", "'" .. text1 .. "' -> '" .. trimmed1 .. "'")
-- 示例2: 修剪特定字符
local text2 = "***hello world***"
local trimmed2 = strutils.trim(text2, "*")
print("修剪星号:", "'" .. text2 .. "' -> '" .. trimmed2 .. "'")
-- 示例3: 修剪混合字符
local text3 = "###---hello world---###"
local trimmed3 = strutils.trim(text3, "#-")
print("修剪混合:", "'" .. text3 .. "' -> '" .. trimmed3 .. "'")
-- 示例4: 左右分别修剪
local text4 = " hello world "
local left_trimmed = strutils.ltrim(text4)
local right_trimmed = strutils.rtrim(text4)
print("左修剪:", "'" .. left_trimmed .. "'")
print("右修剪:", "'" .. right_trimmed .. "'")
-- 示例5: 处理用户输入
function clean_user_input(input)
return strutils.trim(input)
end
local user_input = " john.doe@example.com "
local cleaned = clean_user_input(user_input)
print("清理用户输入:", "'" .. user_input .. "' -> '" .. cleaned .. "'")4. 字符串替换 (strutils.replace)
说明: 字符串替换
函数: strutils.replace(str, from, to, count)
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
| str | 字符串 | 原始字符串 |
| from | 字符串 | 要替换的子字符串 |
| to | 字符串 | 替换为的字符串 |
| count | 数字 | 可选,替换次数,默认为全部替换 |
返回值:
| 返回值类型 | 说明 |
|---|---|
| 字符串, 数字 | 返回替换后的字符串和实际替换次数 |
示例:
lua
-- 示例1: 基本替换
local text1 = "hello world hello everyone"
local new_text1, count1 = strutils.replace(text1, "hello", "hi")
print("替换结果:", new_text1)
print("替换次数:", count1)
-- 示例2: 限制替换次数
local text2 = "apple apple apple apple"
local new_text2, count2 = strutils.replace(text2, "apple", "orange", 2)
print("限制替换:", new_text2)
print("实际替换:", count2)
-- 示例3: 空字符串替换
local text3 = "test"
local new_text3 = strutils.replace(text3, "", "X")
print("空替换:", new_text3)
-- 示例4: 模板替换
function format_template(template, variables)
local result = template
for key, value in pairs(variables) do
result = strutils.replace(result, "{{" .. key .. "}}", value)
end
return result
end
local template = "Hello {{name}}, welcome to {{city}}!"
local variables = {name = "John", city = "Beijing"}
local formatted = format_template(template, variables)
print("模板替换:", formatted)
-- 示例5: 多级替换
local text5 = "aabbccddee"
-- 先替换aa为XX,再替换cc为YY
local step1 = strutils.replace(text5, "aa", "XX")
local step2 = strutils.replace(step1, "cc", "YY")
print("多级替换:", step2)5. 检查字符串前缀 (strutils.startswith)
说明: 检查字符串前缀
函数: strutils.startswith(str, prefix, start)
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
| str | 字符串 | 要检查的字符串 |
| prefix | 字符串 | 前缀字符串 |
| start | 数字 | 可选,开始检查的位置 |
返回值:
| 返回值类型 | 说明 |
|---|---|
| 布尔 | 返回布尔值,表示是否以指定前缀开始 |
示例:
lua
-- 示例1: 基本前缀检查
local filename = "document.pdf"
local is_pdf = strutils.startswith(filename, "document")
print("是否以'document'开头:", is_pdf)
local is_txt = strutils.startswith(filename, "text")
print("是否以'text'开头:", is_txt)
-- 示例2: URL协议检查
local url = "https://www.example.com"
local is_https = strutils.startswith(url, "https://")
print("是否是HTTPS协议:", is_https)
-- 示例3: 指定开始位置
local text = "hello world"
local starts_with_world = strutils.startswith(text, "world", 6)
print("从位置6开始是否以'world'开头:", starts_with_world)
-- 示例4: 文件类型检查函数
function get_file_type(filename)
if strutils.startswith(filename, "http://") or strutils.startswith(filename, "https://") then
return "url"
elseif strutils.startswith(filename, "/") or strutils.startswith(filename, "./") then
return "local_path"
elseif strutils.endswith(filename, ".txt") then
return "text_file"
elseif strutils.endswith(filename, ".jpg") or strutils.endswith(filename, ".png") then
return "image_file"
else
return "unknown"
end
end
local files = {
"https://example.com/image.jpg",
"/usr/local/file.txt",
"document.pdf",
"./config.json"
}
print("\n文件类型检测:")
for i, file in ipairs(files) do
print(file, "->", get_file_type(file))
end6. 检查字符串后缀 (strutils.endswith)
说明: 检查字符串后缀
函数: strutils.endswith(str, suffix, end)
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
| str | 字符串 | 要检查的字符串 |
| suffix | 字符串 | 后缀字符串 |
| end | 数字 | 可选,结束检查的位置 |
返回值:
| 返回值类型 | 说明 |
|---|---|
| 布尔 | 返回布尔值,表示是否以指定后缀结束 |
示例:
lua
-- 示例1: 基本后缀检查
local filename = "document.pdf"
local is_pdf = strutils.endswith(filename, ".pdf")
print("是否以'.pdf'结尾:", is_pdf)
local is_txt = strutils.endswith(filename, ".txt")
print("是否以'.txt'结尾:", is_txt)
-- 示例2: 文件扩展名检查
function get_file_extension(filename)
local extensions = {".txt", ".pdf", ".jpg", ".png", ".mp4"}
for _, ext in ipairs(extensions) do
if strutils.endswith(filename, ext) then
return ext
end
end
return "unknown"
end
local test_files = {
"report.pdf",
"image.jpg",
"data.txt",
"video.mp4",
"unknown_file"
}
print("\n文件扩展名检测:")
for i, file in ipairs(test_files) do
print(file, "->", get_file_extension(file))
end
-- 示例3: 域名检查
local domains = {
"www.example.com",
"blog.example.org",
"api.example.net",
"test.example.co.uk"
}
print("\n域名类型检查:")
for i, domain in ipairs(domains) do
local is_com = strutils.endswith(domain, ".com")
local is_org = strutils.endswith(domain, ".org")
local is_net = strutils.endswith(domain, ".net")
print(domain, "com:", is_com, "org:", is_org, "net:", is_net)
end7. 转换为大写 (strutils.upper)
说明: 转换为大写
函数: strutils.upper(str)
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
| str | 字符串 | 要转换的字符串 |
返回值:
| 返回值类型 | 说明 |
|---|---|
| 字符串 | 返回转换为大写的字符串 |
示例:
lua
-- 示例1: 基本大写转换
local text1 = "Hello World"
local upper1 = strutils.upper(text1)
print("原始:", text1)
print("大写:", upper1)
-- 示例2: 混合大小写转换
local text2 = "HeLLo WoRLd"
local upper2 = strutils.upper(text2)
print("混合大小写:", text2)
print("转换结果:", upper2)
-- 示例3: 包含数字和符号
local text3 = "user123@example.com"
local upper3 = strutils.upper(text3)
print("包含数字符号:", text3)
print("转换结果:", upper3)
-- 示例4: 多语言支持
local text4 = "café naïve façade"
local upper4 = strutils.upper(text4)
print("多语言文本:", text4)
print("大写结果:", upper4)
-- 示例5: 数据库查询规范化
function normalize_query(query)
local keywords = {"SELECT", "FROM", "WHERE", "AND", "OR", "ORDER BY", "GROUP BY"}
local normalized = strutils.upper(query)
-- 在实际应用中,这里可能会有更复杂的SQL解析
for _, keyword in ipairs(keywords) do
normalized = strutils.replace(normalized, keyword, keyword)
end
return normalized
end
local sql_query = "select * from users where name = 'john' and age > 25"
local normalized_sql = normalize_query(sql_query)
print("SQL查询规范化:")
print("原始:", sql_query)
print("规范:", normalized_sql)
-- 示例6: 常量定义检查
function is_constant_style(str)
local upper_str = strutils.upper(str)
return str == upper_str
end
local test_constants = {"MAX_SIZE", "API_KEY", "configFile", "userName"}
print("\n常量命名风格检查:")
for i, constant in ipairs(test_constants) do
print(constant, "->", is_constant_style(constant))
end
-- 示例7: 文件名统一处理
function standardize_filename(filename)
local name, ext = filename:match("(.+)%.(.+)$")
if name and ext then
return strutils.upper(name) .. "." .. strutils.lower(ext)
else
return strutils.upper(filename)
end
end
local filenames = {
"readme.TXT",
"INDEX.HTML",
"Main.Cpp",
"CONFIG.JSON"
}
print("\n文件名标准化:")
for i, filename in ipairs(filenames) do
print(filename, "->", standardize_filename(filename))
end8. 转换为小写 (strutils.lower)
说明: 转换为小写
函数: strutils.lower(str)
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
| str | 字符串 | 要转换的字符串 |
返回值:
| 返回值类型 | 说明 |
|---|---|
| 字符串 | 返回转换为小写的字符串 |
示例:
lua
-- 示例1: 基本小写转换
local text1 = "Hello World"
local lower1 = strutils.lower(text1)
print("原始:", text1)
print("小写:", lower1)
-- 示例2: 混合大小写转换
local text2 = "HeLLo WoRLd"
local lower2 = strutils.lower(text2)
print("混合大小写:", text2)
print("转换结果:", lower2)
-- 示例3: 包含数字和符号
local text3 = "User123@Example.COM"
local lower3 = strutils.lower(text3)
print("包含数字符号:", text3)
print("转换结果:", lower3)
-- 示例4: 多语言支持
local text4 = "CAFÉ NAÏVE FAÇADE"
local lower4 = strutils.lower(text4)
print("多语言文本:", text4)
print("小写结果:", lower4)
-- 示例5: 电子邮件地址规范化
function normalize_email(email)
local trimmed = strutils.trim(email)
return strutils.lower(trimmed)
end
local emails = {
"John.Doe@Example.COM",
" ALICE@TEST.ORG ",
"Bob.Smith@Company.COM"
}
print("\n电子邮件规范化:")
for i, email in ipairs(emails) do
print("原始:", "'" .. email .. "'")
print("规范:", "'" .. normalize_email(email) .. "'")
print()
end
-- 示例6: URL路径处理
function normalize_url_path(path)
-- 移除首尾斜杠并转换为小写
local trimmed = strutils.trim(path, "/")
return "/" .. strutils.lower(trimmed) .. "/"
end
local url_paths = {
"/API/Users/List",
"/admin/Dashboard/",
" /PRODUCTS/ITEMS "
}
print("\nURL路径规范化:")
for i, path in ipairs(url_paths) do
print("原始:", "'" .. path .. "'")
print("规范:", "'" .. normalize_url_path(path) .. "'")
print()
end
-- 示例7: 配置键名统一
function normalize_config_keys(config_table)
local normalized = {}
for key, value in pairs(config_table) do
local normalized_key = strutils.lower(key)
normalized[normalized_key] = value
end
return normalized
end
local config = {
["DATABASE_HOST"] = "localhost",
["Database_Port"] = 5432,
["database_name"] = "mydb",
["API_KEY"] = "secret123"
}
local normalized_config = normalize_config_keys(config)
print("配置键名统一:")
for key, value in pairs(normalized_config) do
print(key, "=", value)
end
-- 示例8: 搜索查询处理
function preprocess_search_query(query)
-- 转换为小写并修剪
local cleaned = strutils.trim(query)
cleaned = strutils.lower(cleaned)
-- 移除多余空格
cleaned = cleaned:gsub("%s+", " ")
return cleaned
end
local search_queries = {
" Hello World ",
"JavaScript AND HTML",
" DATA ANALYSIS "
}
print("\n搜索查询预处理:")
for i, query in ipairs(search_queries) do
print("原始:", "'" .. query .. "'")
print("处理:", "'" .. preprocess_search_query(query) .. "'")
print()
end