0

I'm trying to split a string into two parts, which is divided by a '.' character. But string.find() function cant handle that

I have this kind of string

local test = "345345.57573"

I tried

local start = string.find( test, "." )
local start = string.find( test, "\." )
local start = string.find( test, "(%w+).(%w+)" )

But none of them worked. String.find() always return 1 which is false. What might be the problem?

Edit: I also tried to use gsub and change . with another character but it didn't work either

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Doğancan Arabacı
  • 3,934
  • 2
  • 17
  • 25
  • 1
    possible duplicate of [Finding '.' with string.find()](http://stackoverflow.com/questions/15258313/finding-with-string-find) – finnw Jul 08 '13 at 10:49
  • Ok course if you simply want the two numbers then a = {string.match("2353445.23434","(%w+)%.(%w+)")} will return a table with the numbers in. – Jane T Jul 08 '13 at 16:37

2 Answers2

5

Just use %. in a pattern to match.

local start = string.find( test, "%." )

Unlike many other languages, Lua uses % to escape the following magic characters:

( ) . % + - * ? [ ] ^ $

When in doubt, you can escape any non-alphanumeric character with %, Lua is fine with it even if the character isn't one of the magic characters.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
2

Try this example

function split(pString, pPattern)

    if string.find(pString,".") then
        pString = string.gsub(pString,"%.","'.'")
    end

    if pPattern == "." then
        pPattern = "'.'"
    end

    local Table = {}  -- NOTE: use {n = 0} in Lua-5.0
    local fpat = "(.-)" .. pPattern
    local last_end = 1
    local s, e, cap = pString:find(fpat, 1)
    while s do
        if s ~= 1 or cap ~= "" then
            table.insert(Table,cap)
        end
        last_end = e+1
        s, e, cap = pString:find(fpat, last_end)
    end
    if last_end <= #pString then
        cap = pString:sub(last_end)
        table.insert(Table, cap)
    end

    return Table
end

local myDataTable = split("345345.57573",".")

--Loop Through and print the last split data table

print(myDataTable[1]) --345345
print(myDataTable[2]) --57573

Reference

NaviRamyle
  • 3,967
  • 1
  • 31
  • 49