-- 1. 写一个函数,提取字符串中所有邮箱地址(格式:xxx@yyy.zzz)。
local function matchEmail(s) local emails = {} for email in string.gmatch(s, "[%w%.%-_]+@[%w%.%-_]+%.%a+") do table.insert(emails, email) end return emails end local t = matchEmail("请联系我:test123@abc.com 或者 other_mail@163.cn,谢谢") for _, e in ipairs(t) do print(e) end
-- 2. 编写函数,判断一个字符串是否只包含字母和数字。
local function isAlnum(s) return s:match("^[%w]+$") ~= nil end print(isAlnum("abc123")) -- true print(isAlnum("abc-123")) -- false
-- 3. 编写函数,找出字符串中第一个不重复的字符。
local function firstUniqueChar(s) local freq = {} for c in s:gmatch(".") do freq[c] = (freq[c] or 0) + 1 end for i = 1, #s do local c = s:sub(i,i) if freq[c] == 1 then return c end end return nil end print(firstUniqueChar("abcdadbcg")) -- g
-- 4.写一个函数,提取 URL 中的域名(例如从 https://openai.com/docs 提取 openai.com)。
local function getUrlName(s) if type(s) ~= "string" then print("请输入字符串") return nil end return s:match("://([^/]+)") end print(getUrlName("https://openai.com/docs"))
-- 5. 编写函数,将字符串中的所有 HTML 标签去掉,只保留纯文本。
local str = "<p>Hello</p><b>World</b>" local newStr, count = str:gsub("<.->", "") print(newStr)