【问题标题】:I need to split string from a character我需要从一个字符中拆分字符串
【发布时间】:2023-04-29 14:14:01
【问题描述】:

我的字符串是

text1,text2

我想用 ',' 分割 text1 和 text2。

【问题讨论】:

    标签: lua love2d


    【解决方案1】:

    试试这个:

    s="text1,text2"
    t1,t2=s:match("(.-),(.-)$")
    print(t1,t2)
    

    【讨论】:

    • 令人着迷,每次我用我所知道的回答一个 lua 问题时,我都会从其他答案中学到一些新东西 :) +1
    【解决方案2】:

    要获得带有子字符串的迭代器,您可以调用string.gmatch

    for i in string.gmatch(example, "%P+") do
      print(i)
    end
    

    要将它们分成两个单独的字符串,您可以调用迭代器;

    > iter = string.gmatch(indata, "%P+")
    > str1 = iter()
    > str2 = iter()
    > print (str1)
    test1
    > print (str2)
    test2
    

    如果您希望将它们存储在一个数组中,有一个完整的讨论 here 如何实现。

    @lhf 在 cmets 中添加了一个更好的模式 [^,]+,我的在任何标点符号上都分开,他只在逗号上。

    【讨论】:

    • 我可以把'text1'和'text2'两个字符串放在一起吗?
    • 最好使用"[^,]+",以防其中一个字段有标点符号。
    【解决方案3】:

    试试本页给出的功能:

    http://lua-users.org/wiki/SplitJoin

    【讨论】:

      最近更新 更多