解決方案取決於您期望的括號之間的模式,您尚未指定。 (例如,對於"(st12uv)"
,您可能需要["st", "12", "uv"]
,["st12", "uv"]
,["st1", "2uv"]
等)。如果,在你的榜樣,它是一個自然數後跟一個+
,緊接着又自然數,你可以這樣做:
str = "1-(2+ 3)"
r =/
\(\s* # match a left parenthesis followed by >= 0 whitespace chars
(\d+) # match one or more digits in a capture group
\s* # match >= 0 whitespace chars
(\+) # match a plus sign in a capture group
\s* # match >= 0 whitespace chars
(\d+) # match one or more digits in a capture group
\s* # match >= 0 whitespace chars
\) # match a right parenthesis
/x
str.scan(r0).first
=> ["2", "+", "3"]
假設,而不是+
可能是+
,-
,*
或/
。然後,你可以更改:
(\+)
到:
([-+*\/])
需要注意的是,在一個字符類,+
不需要進行轉義,如果它是第一個或最後一個字符-
不需要進行轉義(在這種情況下,它不代表範圍)。
順便提一下,您收到錯誤消息「無效的後向模式」,因爲Ruby的週期不能包含可變長度匹配(即.*
)。通過使用\K
來代替積極向後看,你可以解決這個問題。例如,
r =/
\d+ # match one or more digits
\K # forget everything previously matched
[a-z]+ # match one or more lowercase letters
/x
"123abc"[r] #=> "abc"
我覺得stringscanner更適合這類任務。 –
無效的消息似乎是因爲在大多數引擎中(除了Dot-Net),lookbehinds不能具有可變長度。另一件事是,如果你試圖獨立解析'(2 + 3)',除非Ruby支持遞歸,否則你不能這麼做。而且,我不知道它是否。另一種方法是自己解析它,逐個字符地跟蹤堆棧的嵌套。 – sln
這將是一個適當的嵌套示例:'(5-(3 * 2(4 + 1)-9)+7)* 4' – sln