【问题标题】:Split string and replace dot char in Lua在Lua中拆分字符串并替换点字符
【发布时间】:2012-08-17 23:30:08
【问题描述】:

我有一个存储在 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 中发布的其他问题,但运气为零

【问题讨论】:

  • "%."是正确的模式,请在 Lua 控制台中尝试。任何以 % 开头的非字母数字字符都表示该字符。

标签: string join lua split newline


【解决方案1】:

这个解决方案怎么样:`

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

【讨论】:

  • 您的解决方案也有效!也谢谢你。我可以检查是否与您的匹配(无)?
  • match 如果没有匹配则返回 nil(对于 a 和 b)。由于定义了正则表达式,这仅适用于空字符串。 Appart 根据您的应用条件,您必须调整正则表达式:开头的点、结尾的点、无点、多个点、连续点等。
  • 感谢您提供的有用信息!
【解决方案2】:

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

--[[

    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

【讨论】:

  • 这就是我真正想要的。非常感谢!
猜你喜欢
  • 2016-08-25
  • 2021-12-11
  • 2010-11-28
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2019-03-08
相关资源
最近更新 更多