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

3

我在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

我尝试了其他在stackoverflow上发布的问题,但没有成功。


"%."是正确的模式,请在Lua控制台中尝试。任何非字母数字字符前面加上%表示该字符。 - Adam
2个回答

5
这个解决方案怎么样:`
s = "First line and string. This should be another string in a new line"
a,b=s:match"([^.]*).(.*)"
print(a)
print(b)

你的解决方案也有效!谢谢你。我可以检查一下是否与你的匹配(nil)吗? - Mustafa
如果a和b都没有匹配,match将返回nil。由于正则表达式是这样定义的,只有空字符串才会出现这种情况。除此之外,您需要根据应用程序条件调整正则表达式:在开头加上点、在结尾加上点、没有点、多个点、连续点等。 - hendrik

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

这正是我正在寻找的。非常感谢! - Mustafa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接