Find String Inside Outermost Parenthesis(在最外括号内查找字符串)
问题描述
假设我有一个包含多组括号和嵌套括号的字符串.我只想提取遇到的第一个括号中的字符串,包括它包含的任何嵌套括号.
Say that I have a string which contains both multiple sets and nesting of parenthesis. I want to extract only the string in the first parenthesis encountered, including whatever nested parenthesis it contains.
例如:
这(是(也许))一个测试(也许不是)
this (is(maybe)) a test (and maybe not)
我要提取:
是(也许)
我相信这可以在不使用正则表达式的情况下完成,通过它我可以轻松做到.
I believe this can be accomplished without the use of regexes, by which I can easily do it.
所以我的问题是如何在没有正则表达式的情况下实现这一点?
So my question is how can this be accomplished without regexes?
推荐答案
以免伪代码成为我自己使用标准算法回答这个问题的唯一答案.鉴于 const string foo{ "this (is(maybe)) a test (and may not)" }
c++14 可以这样解决:
Lest pseudo code be the only answer I've taken it upon myself to answer this using standard algorithms. Given const string foo{ "this (is(maybe)) a test (and maybe not)" }
c++14 can be used to solve like this:
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
和 finish
都不是 cend(foo)
字符串是有效的,可以从 获得字符串(下一个(开始),完成)
(现场示例).
From here, if both start
and finish
are not cend(foo)
the string is valid and can be obtained from string(next(start), finish)
(Live Example).
这可能是一个与 C++ 中一样好的解决方案.我想这只是一厢情愿的想法,有一些东西可以匹配括号并找到值.
It's possible that this is as good a solution as there is in C++. I guess it is just wishful thinking that there's something out there to match parentheses and find the value.
这篇关于在最外括号内查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在最外括号内查找字符串
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01