解决方案取决于您期望的括号之间的模式,您尚未指定。 (例如,对于"(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