【问题标题】:Corona string.find() : Finding "."电晕 string.find() :寻找“。”
【发布时间】:2013-07-05 12:49:26
【问题描述】:

我试图将一个字符串分成两部分,由'.' 字符分割。但是string.find() 函数无法处理

我有这种字符串

local test = "345345.57573"

我试过了

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

但他们都没有工作。 String.find() 总是返回 1 这是错误的。 可能是什么问题?

编辑: 我还尝试使用 gsub 并更改 .与另一个角色,但它也不起作用

【问题讨论】:

  • Finding '.' with string.find() 的可能重复项
  • 好吧,如果你只是想要两个数字,那么 a = {string.match("2353445.23434","(%w+)%.(%w+)")} 将返回一个包含数字的表格在。

标签: string lua coronasdk lua-patterns


【解决方案1】:

只需在要匹配的模式中使用%.

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

与许多其他语言不同,Lua 使用% 来转义以下魔术字符:

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

如有疑问,您可以使用 % 转义任何非字母数字字符,即使该字符不是魔法字符之一,Lua 也可以。

【讨论】:

    【解决方案2】:

    试试这个例子

    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

    【讨论】:

    • 谢谢,它完美无瑕。看来我应该使用“%”。代替 ”。”这也能解决问题..
    猜你喜欢
    • 2013-02-21
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多