在c++中使用std::regex获得最小匹配
Get smallest match using std::regex in C++
我有这样的代码:
std::smatch m;
std::string dataType = "type = struct A {nint a;nint b;nint c; }";
std::regex_search(dataType, m, std::regex("(= )(.*)( [{]|n|$)"));
std::cout << m.str(2) << std::endl;
问题是它返回最长的匹配,但我需要最小的匹配。输出为:
struct A {n int a;n int b;n int c; }
但必须是:
struct
我怎样才能得到我想要的结果?
可以将.*
改为.*?
了解贪婪。
(你真的想在正则表达式中放一个换行符吗?你可能想把它改成\n
)
要从文本中获取"struct A",要使用的正则表达式是:
=s(w+sw+)
如果你有其他情况,请给出更多的说明或例子,你的输入和输出应该是什么样子的。
编辑:感谢user3259253,正确的解决方案是:
\=\s(\w+(\s\w+)?)
正确,使用
std::regex_search(dataType, m, std::regex("(= )(.*)([\{]|\n)$"));
但是,如果您只想捕获=符号和花括号/行尾之间的内容,则不需要那么多()组。这就足够了:
std::regex_search(dataType, m, std::regex("= (.*)[\{]|\n$"));
std::cout << m.str(1) << std::endl;
请注意,这里我们捕获的文本作为第一个条目,m.str(1),而不是第二个条目,因为我们已经消除了"(=)"相关文章:
- C++ std::regex 使用前瞻失败
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- 在VC2015U3上,std::regex比boost::regex慢得多
- 将std::regex设置为静态的好主意吗
- std::regex and dual ABI
- C++11 std::regex后备选项
- 包含在 std::regex 搜索中,使用 std::regex_token_iterator 从 std::sub_m
- std::string references、std::regex和boost::filesystem的基本概念
- std::regex 是否保证了最坏情况下的时间复杂度?
- boost::regex 和std::regex之间的不一致?
- <regex> std::regex 等同于 Qt 的 QRegularExpression::isValid() 而不触发异常
- “Multiline”不是“std::__cxx11::regex”的成员
- 使用 std::regex 拆分一行并丢弃空元素
- std::string to std::regex
- 用std :: Regex通过DOT解析数字
- C++ [std::regex] 尝试仅匹配中间有空格的数字
- std::regex总是可以识别区域设置吗?
- 是STD :: REGEX构造函数安全
- STD :: Regex不确定的行为