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