【问题标题】:Lua pattern separating issueLua 模式分离问题
【发布时间】:2013-10-29 06:41:21
【问题描述】:

我需要一些帮助来创建我的模式。我已经完成了基本部分,但还有一个问题。

假设我有一个字符串如下:

John: I can type in :red:colour! :white:Not in the same :red:wo:green:rd :white:though :(

我有这个代码设置来将颜色与实际值分开:

line = "John: I can type in :red:colour! :white:Not in the same :red:wo:green:rd :white:though :("

for token in string.gmatch(line, "%s?[(%S)]+[^.]?") do
   for startpos, token2, endpos in string.gmatch(token, "()(%b::)()") do
      print(token2)
      token = string.gsub(token, token2, "")
   end
   print(token)
end

将输出:

John: 
I 
can 
type 
in 
:red:
colour! 
:white:
Not 
in 
the 
same 
:red:
:green:
word 
:white:
though 
:(

当我希望它打印出来时:

John: 
I 
can 
type 
in 
:red:
colour! 
:white:
Not 
in 
the 
same 
:red:
wo
:green:
rd 
:white:
though 
:(

任何帮助将不胜感激。

【问题讨论】:

    标签: string lua string-matching lua-patterns


    【解决方案1】:

    更通用的解决方案有效:

    line = "John: I can type in :red:colour! :white:Not in the same :red:wo:green:rd :white:though :("

    for i in string.gmatch(line ,"%S+") do
        if (i:match(":%w+")) then
            for k,r in string.gmatch(i,"(:%w+:)(%w+[^:]*)") do
                print(k)
                print(r)
            end
        else
            print(i)
        end
    end
    

    也适用于字符串:“in the sa:yellow:me:pink:long-Words!”

    【讨论】:

      【解决方案2】:

      下面的代码会给你desired output:

      for token in line:gmatch( "(%S+)" ) do
        if not token:match( "(:%w-:)([^:]+)" ) then
          print(token)
        else
          for col, w in token:gmatch( "(:%w-:)([^:]+)" ) do
            print( col )
            print( w )
          end
        end
      end
      

      不过,对于如下字符串会失败:

      in the sa:yellow:me:pink:long-Words!
      

      【讨论】:

      • 这部分完成了这项工作,但是当有人键入诸如“00:20:14”之类的内容时,前两个零会消失。任何帮助将不胜感激:)
      • @user1773027 如果您确定只使用:red: 格式的颜色,那么您可以使用(:%a-:) 代替(:%w-:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      相关资源
      最近更新 更多