拆分字符串并替换Lua中的dot char

时间:2012-08-17 23:30:09

标签: string join lua split newline

我有一个存储在sqlite数据库中的字符串,我已将其分配给var,例如串

string =“第一行和字符串。这应该是新行中的另一个字符串”

我想将此字符串拆分为两个单独的字符串,点(。)必须替换为(\ n)新行字符

此刻我被困住了,任何帮助都会很棒!!

for row in db:nrows("SELECT * FROM contents WHERE section='accounts'") do
    tabledata[int] = string.gsub(row.contentName, "%.", "\n")
    int = int+1
end

我尝试了stachoverflow中发布的其他问题,但没有运气

2 个答案:

答案 0 :(得分:1)

您是否希望将字符串实际拆分为两个不同的字符串对象?如果是这样,这可能有所帮助。这是我写的一个函数,用于向标准字符串库添加一些额外的功能。您可以按原样使用它或将其重命名为您喜欢的任何内容。

--[[

    string.split (s, p)
    ====================================================================
    Splits the string [s] into substrings wherever pattern [p] occurs.

    Returns: a table of substrings or, if no match is made [nil].

--]]
string.split = function(s, p)
    local temp = {}
    local index = 0
    local last_index = string.len(s)

    while true do
        local i, e = string.find(s, p, index)

        if i and e then
            local next_index = e + 1
            local word_bound = i - 1
            table.insert(temp, string.sub(s, index, word_bound))
            index = next_index
        else            
            if index > 0 and index <= last_index then
                table.insert(temp, string.sub(s, index, last_index))
            elseif index == 0 then
                temp = nil
            end
            break
        end
    end

    return temp
end

使用它非常简单,它返回一个字符串表。

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> s = "First line and string. This should be another string in a new line"
> t = string.split(s, "%.")
> print(table.concat(t, "\n"))
First line and string
 This should be another string in a new line
> print(table.maxn(t))
2

答案 1 :(得分:1)

这个解决方案怎么样:`

s = "First line and string. This should be another string in a new line"
a,b=s:match"([^.]*).(.*)"
print(a)
print(b)