2017-10-08 14 views
0

我有一個在Lua我的正則表達式不工作的麻煩。我已經在其他環境中測試過它,比如我的文本編輯器和一些在線正則表達式工具,它似乎在那裏工作得很好。正則表達式的作品隨處可見,但在Lua

正則表達式的作品我怎麼想,在其他環境:

RAY\.decrypt\s*\(([\"\'].+?(?=[\"\']).+?(?=[\)]))\s*\) 

是正則表達式我試圖在Lua使用(只需\ S的同%替換成')

RAY%.decrypt%s*%(([\"\'].+?(?=[\"\']).+?(?=[%)]))%s*%) 

我想要匹配的示例文本(我想捕捉在括號中的內容)

RAY.decrypt ("\x02\x02\x02\x02\x02\x02\x02\x02") 
RAY.decrypt ("\xd6E\xd6E\xd6E\xd6E\xd6E") 
RAY.decrypt("\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e") 

其他工具米抓住文本並捕捉我想要捕捉的東西,完美。但我正在努力讓Lua做到這一點,因爲它與任何東西都不匹配。

local s = [[RAY.decrypt ("\x02\x02\x02\x02\x02\x02\x02\x02") 
RAY.decrypt ("\xd6E\xd6E\xd6E\xd6E\xd6E") 
RAY.decrypt("\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e")]] 

print(string.find(s, "RAY%.decrypt%s*%(([\"\'].+?(?=[\"\']).+?(?=[%)]))%s*%)")) 
> nil 

任何幫助,將不勝感激,謝謝!

回答

0

我根本不知道LUA,但是維基百科關於LUA正則表達式引擎的說法是: 「使用簡化的,有限的方言;可以綁定到更強大的庫,如PCRE或像LPeg這樣的替代解析器。

所以,你要麼把它綁定到PCRE,或者你不應該比其他引擎,只是用LUA文件專門編寫正則表達式LUA,不是你的文本編輯器。

+1

非常感謝你。看來Lua正則表達式引擎不支持向前看,這解釋了爲什麼它不起作用。 – lewez

1
local s = [[ 
RAY.decrypt ("\x02\x02\x02\x02\x02\x02\x02\x02") 
RAY.decrypt ('\xd6E\xd6E\xd6E\xd6E\xd6E') 
RAY.decrypt("\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e") 
]] 

for w in s:gmatch"RAY%.decrypt%s*%(%s*(([\"']).-%2)%s*%)" do 
    print(w) 
end 

輸出:

"\x02\x02\x02\x02\x02\x02\x02\x02" 
'\xd6E\xd6E\xd6E\xd6E\xd6E' 
"\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e" 
0

Lua的標準字符串庫不支持完整的正則表達式,但它的模式匹配是相當強大的。

這個腳本匹配括號內的一切:

for w in s:gmatch("%((.-)%)") do 
    print(w) 
end 
+0

如果文字字符串包含右括號?原正則表達式照顧它:'RAY \ .decrypt \ S * \(?([\ 「\']。?+(= [\」 \'])+(= [\)]))\ S * \)' –

0

Lua中內置的「正則表達式」被稱爲「模式」

這配襯內容括號

local source = [[ 
    RAY.decrypt ("\x02\x02\x02\x02\x02\x02\x02\x02") 
    RAY.decrypt ("\xd6E\xd6E\xd6E\xd6E\xd6E") 
    RAY.decrypt("\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e") 
]] 

-- this captures expressions containing RAY.decrypt (" ... ") 
for content in string.gmatch(source , "RAY%.decrypt%s*%(%s*\"(.-)\"%s*%)") do 
    print(content) 
end 

-- this captures expressions inside double quotes 
for content in string.gmatch(source , "\"(.-)\"") do 
    print(content) 
end 

-- this captures expressions inside single or double quotes e.g. RAY.decrypt ('\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e') 
for content in string.gmatch(source , "[\"'](.-)[\"']") do 
    print(content) 
end 

-- this captures expressions inside parentheses (will capture the quotes) 
for content in string.gmatch(source , "%((.-)%)") do 
    print(content) 
end 
相關問題