Lua模式分隔问题

我需要在创建模式时得到一些帮助。我已经完成了基本部分,现在只剩一个问题。

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

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
:(

任何帮助都将不胜感激。

点赞
用户1190388
用户1190388

以下代码将给出你期望的输出:

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!
2013-10-20 22:19:43
用户2239760
用户2239760

更通用的解决方案:

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

也适用于字符串:"在相:yellow:同:pink:长的单词中!"

2016-03-10 15:27:18