"382 + 323"또는 "32x291"또는 "94-23"과 같은 루아 문자열이 있는데 어떻게 피연산자의 위치를 확인하고 반환 할 수 있습니까?Lua가 문자열에서 피연산자를 찾음
String.find(s, "[+x-]")
이 작동하지 않습니다. 어떤 아이디어?
th> str = '5+3'
th> string.find(str, '[+-x]')
1 1
th> string.find(str, '[+x-]')
2 2
"382 + 323"또는 "32x291"또는 "94-23"과 같은 루아 문자열이 있는데 어떻게 피연산자의 위치를 확인하고 반환 할 수 있습니까?Lua가 문자열에서 피연산자를 찾음
String.find(s, "[+x-]")
이 작동하지 않습니다. 어떤 아이디어?
th> str = '5+3'
th> string.find(str, '[+-x]')
1 1
th> string.find(str, '[+x-]')
2 2
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
는 [-x +] '+'및 'X'사이의 범위에서 1 개 문자 패턴 매치이다. 대시를 문자로 사용하고 메타 문자로 사용하지 않으려면 문자 그룹을 시작하거나 종료해야합니다.
[작동] (http://ideone.com/ZPKl34). 테스트 케이스를 포함하여 정확한 코드를 보여주십시오. –
"[+ x-]"는 작동하지만 "[+ -x]"는 다른 결과를 반환합니다. 왜? –
"-"는'[]'세트 안에있는 특수 문자입니다. '[+ -x]'를 쓰면'[a-z]'와 같이 문자 범위로 해석되지만'-'가 마지막 문자로 나타나면 그냥'-'로 취급됩니다. – hugomg