2011-03-11 68 views
0

我遇到了一個Lua 5.0正則表達式,將適用於2場景的麻煩。遇到麻煩提出了一個正則表達式

1)表達= "[^V]Core %d+:%s*%+(%d+%.%d+)°C %(crit = %+(%d+%.%d+)°C%)" 這此字符串正確匹配:

Core 0:  +45.0°C (high = +86.0°C, crit = +100.0°C) 

然而,我想能夠:

Core 0:  +45.0°C (crit = +100.0°C) 

2)表達= "[^V]Core %d+:%s*%+(%d+%.%d+)°C %(high = %+%d+%.%d+°C, crit = %+(%d+%.%d+)°C%)" 此正確此字符串相匹配匹配任一個字符串並且有2個捕獲:第一個溫度和臨界溫度。 (我不需要高溫)。 我試過,但沒有運氣:

expression = "[^V]Core %d+:%s*%+(%d+%.%d+)°C %((?:high = %+%d+%.%d+°C,)crit = %+(%d+%.%d+)°C%)" 

我在Lua但我覺得正則表達式語法緊密匹配其他語言如Perl。 任何人有任何想法?

+2

我真的希望溫度永遠不會是負面的:-) – AndersH 2011-03-13 10:34:16

回答

1

的Lua的字符串patterns正則表達式

爲了做到你想要的 - 匹配兩個不同的字符串 - 你需要實際嘗試兩個匹配。

local input = ... -- the input string 
-- try the first pattern 
local temp, crit = string.match(input, "[^V]Core %d+:%s*%+(%d+%.%d+)°C %(crit = %+(%d+%.%d+)°C%)" 
-- if it didn't match, try the second match 
if not temp then 
    temp, crit = string.match(input, "[^V]Core %d+:%s*%+(%d+%.%d+)°C %(high = %+%d+%.%d+°C, crit = %+(%d+%.%d+)°C%)") 
end 
if temp then 
    -- one of the two matches are saved in temp and crit 
    -- do something useful here 
end 
0

我想你需要在(?:...)組後面?

有一些有趣的事情發生在parens之前的空間數量 - 字符串和non-working regexp有兩個,而'working'正則表達式有一個。我會使用%s +來提高健壯性。

+0

我沒有剪切和粘貼,所以我認爲在parens前面有2個空格。但你對使用%s +是正確的。我也嘗試過?在沒有運氣的(?:...)組之後。 – 2011-03-11 16:05:13

+1

好的,現在我實際上查找了LUA的模式文檔。他們甚至沒有原始UNIX正則表達式的實力,實際上它們並不涵蓋數學意義上的正則表達式。括號中沒有量詞,他們只是爲了捕捉,而不是花哨的Perl的東西。你必須放棄匹配可選的高溫部分,只需放入'%(。* crit'跳過它即可。 – LHMathies 2011-03-12 11:22:04

+0

這就是爲什麼它們被稱爲模式,而不是正則表達式。 – 2011-03-12 18:11:56