2012-08-24 232 views
1

簡單的問題可能有一個簡單的答案,但我目前的解決方案看起來很可怕。Lua:如何檢查一個字符串是否只包含數字和字母?

local list = {'?', '!', '@', ... etc) 
for i=1, #list do 
    if string.match(string, strf("%%%s+", list[i])) then 
     -- string contains characters that are not alphanumeric. 
    end 
end 

有沒有更好的方法來做到這一點..也許與string.gsub?

在此先感謝。

+0

什麼是「strf」?什麼是'$ list'?這不是有效的Lua運營商。 –

+0

我創建的東西,它是string.format的簡寫。 –

+0

輸入它有點太快,沒有回頭看,它是固定的:P –

回答

6

如果你想看看是否字符串只包含字母數字字符,那麼就匹配對所有非字母數字字符字符串:

if(str:match("%W")) then 
    --Improper characters detected. 
end 

模式%w匹配字母數字字符。按照慣例,比大寫而不是小寫的模式匹配反轉字符集合。所以%W匹配所有非字母數字字符。

+1

謝謝,我知道有一個簡單的答案:P –

4

您可以創建一個集比賽與[]

local patt = "[[email protected]]" 

if string.match (mystr , patt) then 
    .... 
end 

注意,在LUA該字符類只針對單個字符(沒有的話)工作。 有內置的類,%W匹配非字母數字,所以繼續使用它作爲快捷方式。

您還可以添加內置類的集合:

local patt = "[%Wxyz]" 

將匹配所有非字母數字和字符我用這個Lua的兩班輪xyz

0

local function envIsAlphaNum(sIn) 
    return (string.match(sIn,"[^%w]") == nil) end 

當它檢測到非字母數字時,它將返回錯誤

相關問題