[英]Find String Inside Outermost Parenthesis
假设我有一个包含多个集合和括号嵌套的字符串。 我只想提取遇到的第一个括号中的字符串,包括它包含的任何嵌套括号。
例如:
这(是(也许))测试(也许不是)
我要提取:
是(也许)
我相信,无需使用正则表达式就可以实现此目的,而我可以轻松地做到这一点。
所以我的问题是, 没有正则表达式怎么能做到这一点?
伪代码:
iterate over chars
if char is (
increment counter
store position of first ( only
if char is )
decrement counter
if counter == 0
use index of current char and position of first ( to get substring
唯有伪代码成为我自己使用标准算法来回答这个问题的唯一答案。 给定const string foo{ "this (is(maybe)) a test (and maybe not)" }
c ++ 14可以像这样解决:
const auto start = find(cbegin(foo), cend(foo), '(');
const auto finish = find_if(start, cend(foo), [count = 0](const char i) mutable {
if (i == '('){
count++;
}
else if (i == ')'){
count--;
}
return count <= 0; });
从这里start
,如果start
和finish
都不都是cend(foo)
那么该字符串是有效的,并且可以从string(next(start), finish)
( 实时示例 )。
这可能是和C ++一样好的解决方案。 我想这只是一厢情愿的想法,那里有些东西可以匹配括号并找到其价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.