Abdi
Abdi

Reputation: 1

Have same thing when checking what the function string.match return in Lua

I'm new in lua and in this forum. I'm testing if a string have only a alphanumeric characters.

For this I use string.match function and I test what the function return.

Here my code:

function ReadFistMacAddressFile (_FilePath)

    local file = open(_FilePath, "rb") -- r read mode and b binary mode
    if not file then
        file:close()
        appli.Test_failed("Can't open the file".. _FilePath .. ".\n\n Verify the path.")
        return nil
    end
    
    print("------------------------")
    print("-------------------------")
    local size = sizeFile (file)
    print("     size = " .. size)
    print("")
    print("")
    if size == 0 then
        file:close()
        appli.Test_failed("Mac Adress file's empty")
        return nil
    end
        
    
    local lignes = ReadLine (file, 1)
    print("     lignes = " .. lignes)
    print("")
    print("")
    
    local NoneAlphaNumericFind = nil 
    NoneAlphaNumericFind = string.match(lignes,"[^%w]")
    print("     NoneAlphaNumericFind = " .. NoneAlphaNumericFind)
    print("")
    print("")
    
    if NoneAlphaNumericFind == nil or NoneAlphaNumericFind == '' then
        file:close()
        return lignes
    else
        file:close()
        appli.Test_failed("Mac adress contain the characteres: ".. NoneAlphaNumericFind)    
        return nil 
    end
    
end

I open the mac adress file, read the first line and test if the string have only alphanumeric characters

The problem that I have is I go to else condition in any case. I saw in lua docs that string.match return nil if it doesn't find the pattern, so i don't undestantd why it doesn't work.

Here were there is only alaphanumeric characters

Here were there is a none alaphanumeric characters

I thank you in advance for your help.

I've tried every solution that I saw in this forum and none work.

Upvotes: 0

Views: 50

Answers (1)

ESkri
ESkri

Reputation: 1928

Your file is opened as binary (in rb mode), so CRLF line terminator is not converted to LF.
Only LF is auto-removed by Lua file:lines() and file:read() functions.
So, non-alphanumeric CR char in still in the line returned, it always matches [^%w] pattern.

BTW, Lua has %x pattern to match a hexadecimal digit.
You can use [^%x] or simply %X pattern to find a char which is not from the set 0-9A-Fa-f

Upvotes: 0

Related Questions