java - A "Nice" way to get substring between an opening and a matching closing tag (parantheses etc.) -
i quite run task of extracting substring string located between opening tag (such "(") , closing tag (for example ")"), such "level" of opening tag matches "level" of closing tag.
for example, in following string,
((a + (b * c) + d) + e)
when given index 1 (pointing second opening tag "(" in string), interested in substring
(a + (b * c) + d)
i'm not interested in part until first closing tag:
(a + (b * c)
in addition one-character tags, longer strings (e.g., "begin", "end") should work, too. not hard solve this, find running through string in loop quite ugly, possibly inefficient , error-prone.
is there nice way this?
(maybe there regex hack? won't work directly due need of counting.)
i've had similar this, using <
, >
instead.
the best way in opinion iterate string, , keep stack of 'open' , 'close' tags go along. when hit point number of open , close tags same, know you've found substring. method require recursion/loops once parsed outermost case still have inner cases.
alternatively, same, hit close tag, parse substring of last open tag , close tag. method harder keep track of strings immutable.
if want code examples can provide them, string parsing pretty fun learn
Comments
Post a Comment