我尝试使用clang:
在OSX上的c ++ 11中使用正则表达式库// product format
// "AAPL 150918C00099500"
// python regex
// "(?P<Symbol>[a-zA-Z0-9]+)\s*(?P<Expiry>\d{6})(?P<Payoff>[C|P])(?P<Strike>\d{8})"
#include <string>
#include <regex>
#include <iostream>
int main()
{
std::string s{ "AAPL 150918C00099500" };
std::regex pat{ R"([a-zA-Z0-9]{1,6})\s*(\d{6})([CP]{1})(\d{8})" };
bool isMatch = std::regex_match( s, pat );
std::sregex_iterator it( s.begin(), s.end(), pat );
for( ; it != std::sregex_iterator{}; ++it )
{
std::cout << ( *it )[0] << std::endl;
}
}
以下代码的输出应为:
AAPL
150918
C
00099500
而是吐出来
AAPL
150918
C00099
500
这似乎是一个错误...... 有人知道解决这个问题吗?
由于
系统详情:
$ uname -a
Darwin MBP.fios-router.home 14.5.0 Darwin Kernel Version 14.5.0: Wed Jul 29 02:26:53 PDT 2015; root:xnu-2782.40.9~1/RELEASE_X86_64 x86_64 i386 MacBookPro11,2 Darwin
$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin14.5.0
Thread model: posix
答案 0 :(得分:4)
您需要访问使用regex_match
函数获得的匹配内的捕获组。通过数字索引访问每个捕获组:
std::cout << ( *it )[1] << "\n" << ( *it )[2]<< "\n"
<< ( *it )[3] << "\n" << ( *it )[4] << std::endl;
请参阅IDEONE demo
另外,请注意原始字符串文字正则表达式声明:
std::regex pat{ R"(([a-zA-Z0-9]{1,6})\s*(\d{6})([CP]{1})(\d{8}))" };
^^^ ^^