gpt4 book ai didi

python - C++11 正则表达式混淆

转载 作者:太空宇宙 更新时间:2023-11-03 15:30:18 25 4
gpt4 key购买 nike

我有一个 python 正则表达式:

\A\s*                      # optional whitespace at the start, then
(?P<sign>[-+]?) # an optional sign, then
(?=\d|\.\d) # lookahead for digit or .digit
(?P<num>\d*) # numerator (possibly empty)
(?: # followed by
(?:/(?P<denom>\d+))? # an optional denominator
| # or
(?:\.(?P<decimal>\d*))? # an optional fractional part
(?:E(?P<exp>[-+]?\d+))? # and optional exponent
)
\s*\Z # and optional whitespace to finish

换句话说,获取以下内容的命名组:

  • 签名/​​未签名 |有理数/小数/整数 |数量 |带/不带指数

但是我对 C++11 正则表达式格式感到困惑?正如我所读到的,支持的格式很少,但我遇到了一个正则表达式解析器异常。此外,我了解到 C++11 正则表达式不支持命名组。

如何拥有提供等效方案的 C++11 兼容正则表达式?

非常感谢您的帮助。

最佳答案

您无法保留命名的捕获组,但可以使用多行字符串文字以详细方式定义模式:

std::string pat = "^\\s*"      // optional whitespace at the start, then
"([-+]?)" // an optional sign, then
"(?=\\.?\\d)" // lookahead for digit or .digit
"(\\d*)" // numerator (possibly empty)
"(?:" // followed by
"(?:/(\\d+))?" // an optional denominator
"|" // or
"(?:\\.(\\d*))?" // an optional fractional part
"(?:E([-+]?\\d+))?" // and optional exponent
")"
"\\s*$"; // and optional whitespace to finish
std::regex e(pat);
std::string s(" -23/34 ");
std::smatch a;
if (std::regex_search(s, a, e))
std::cout << a[0] << endl;

请参阅C++ demo

关于python - C++11 正则表达式混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42934997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com