2016-08-15 65 views
2

我有一個類似「382 + 323」或「32x291」或「94-23」的Lua字符串,我該如何檢查並返回操作數的位置?Lua在字符串中查找操作數

我發現String.find(s, "[+x-]")沒有工作。有任何想法嗎?

th> str = '5+3' 
th> string.find(str, '[+-x]') 
1 1 
th> string.find(str, '[+x-]') 
2 2 
+0

[It works](http://ideone.com/ZPKl34)。顯示您的確切代碼,包括測試用例。 –

+0

「[+ x-]」似乎有效,但「[+ -x]」將返回不同的結果。爲什麼? –

+0

「 - 」是'[]'集內的特殊字符。如果你寫'[+ -x]',它將被解釋爲一個字符範圍,比如'[a-z]',但是如果'-'出現作爲最後一個字符,那麼它將被視爲一個'-'。 – hugomg

回答

1
print("Type an arithmetic expression, such as 382 x 3/15") 
expr = io.read() 
i = -1 
while i do 
    -- Find the next operator, starting from the position of the previous one. 
    -- The signals + and - are special characters, 
    -- so you have to use the % char to escape each one. 
    -- [The find function returns the indices of s where this occurrence starts and ends][1]. 
    -- Here we are obtaining just the start index. 
    i = expr:find("[%+x%-/]", i+1) 
    if i then 
     print("Operator", expr:sub(i, i), "at position", i) 
    end 
end 
2

[+ -x]是用於在 「+」 和 「x」 之間的範圍內1個字符的圖案匹配。 當你想使用破折號作爲字符而不是元字符時,你應該用它開始或結束字符組。