Lua操作字符串的5個代碼片段分享
1.匹配字符串中的數(shù)字、字母和下劃線
str = "hello_+asdf2312+887441a+asdf"
table = {}
string.gsub(str, "([%w_]+)",
function(w)
table.insert(table,w)
end
end
2.替換字符串中的指定字符
str = "hello,john"
s = string.gsub(str, "john", "james")
s ==>"hello,james"
3.判斷字符串中是否有目標字串
str = "hello,john"
start, end = string.find(str, "hello")
start ==>1
end ==>5
4.從文件的絕對路徑中獲取到文件名
fn_flag = string.find(filename, "\\")
if fn_flag then
dest_filename = string.match(filename, ".+\\([^\\]*%.%w+)$")
end
fn_flag = string.find(filename, "/")
if fn_flag then
dest_filename = string.match(filename, ".+/([^/]*%.%w+)$")
end
5.去掉字符串中括號內(nèi)的內(nèi)容,并去掉收尾的空格
str = " helloa,ni hao (asdfasdf) "
newstr = string.gsub(str,"%b()","")
newstr = string.gsub(newstr, "^%s*(.-)%s*$", "%1")
print(newstr)---->helloa,ni hao
相關(guān)文章
C++中調(diào)用Lua配置文件和響應函數(shù)示例
這篇文章主要介紹了C++中調(diào)用Lua配置文件和響應函數(shù)示例,本文使用Lua文件作為配置文件,并寫了幾個響應函數(shù)以便在C++中使用,需要的朋友可以參考下2015-07-07Lua中調(diào)用函數(shù)使用點號和冒號的區(qū)別
這篇文章主要介紹了Lua中調(diào)用函數(shù)使用點號和冒號的區(qū)別,本文涉及了Lua中面向?qū)ο蟮囊恍┑闹R,并給出了一個簡單的類代碼實例,需要的朋友可以參考下2014-09-09Lua的編譯、執(zhí)行和調(diào)試技術(shù)介紹
這篇文章主要介紹了Lua的編譯、執(zhí)行和調(diào)試技術(shù)介紹,本文著重講解了對錯誤的處理,另外也講解了編譯和執(zhí)行等知識,需要的朋友可以參考下2015-04-04