Lua中分割字符串并替换点字符

我在 sqlite 数据库中存储了一个字符串,并将其分配给一个变量,例如 string。

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 中发布的其他问题,但是没有任何运气。

点赞
用户415823
用户415823

你是否要将字符串实际分成两个不同的字符串对象?如果是的话,也许这可以帮助你。这是我编写的一个函数,用于为标准字符串库添加一些额外的功能。您可以按原样使用它,也可以根据需要重命名。

--[[
    
    string.split (s, p)
    ====================================================================
    在字符串[s]中,无论何时出现模式[p],都将其拆分成子字符串。
    
    返回:子字符串的表或,如果没有匹配,则为[空]。
    
--]]
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
2012-08-18 00:36:58
用户1560049
用户1560049

这个解决方案怎么样:

s = "第一行的字符串。这应该是在新行中的另一个字符串"
a,b = s:match“([^。] *)。(.*)”
print(a)
print(b)
2012-08-18 08:49:10