2013-10-20 52 views
3

我需要一些帮助来创建我的模式。我已经完成了基本部分,但仍有一个问题。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 
:(

任何帮助将不胜感激。

回答

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! 
+0

这部分完成了这项工作,但是当某人输入诸如“00:20:14”之类的东西时,前两个零就消失了。任何帮助将不胜感激:) – sgtaziz

+1

@ user1773027如果您确定只使用':red:'格式的颜色,那么您可以使用'(:%a - :)'代替' (:%重量 - :)'。 – hjpotter92

+0

我的解决方案也适用于“00:20:14” – tanzil

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 

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