3

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

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

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

任何帮助将不胜感激。

4

2 回答 2

2

以下代码将提供您想要的输出

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-20T22:19:43.990 回答
0

更通用的解决方案有效:

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

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

于 2016-03-10T15:27:18.463 回答