2013-10-20 127 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!」