【整理】C++正则表达式验证期货合约代码

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】C++正则表达式验证期货合约代码

工作中有个小小的需求,获取合约代码的合约品种,那么目前四大交易所的合约代码基本上是按照如下编码:

两位字母+年月,比如cu1709,zn1801,SR801...

或者:

一位字母+年月,比如a1801

那么我所希望提取的仅仅是合约品种,那么只需要通过正则表达式,匹配下字母数字组合即可。代码如下:

// regex_match example
#include <iostream>
#include <string>
#include <regex>

int main ()
{

 char cstr[] = "cu1709";
 std::regex e("[a-zA-Z]{2}[0-9]{3,4}");
 //char cstr[] = "a1701";
 //std::regex e("[a-zA-Z]{1}[0-9]{3,4}");

 if (std::regex_match (cstr, e))
 std::cout << "string object matched\n";

 std::cmatch cm; // same as std::match_results<const char*> cm;
 std::regex_match (cstr,cm,e);
 std::cout << "string literal with " << cm.size() << " matches\n";


 std::cout << "the matches were: ";
 for (unsigned i=0; i<cm.size(); ++i) {
 std::cout << "[" << cm[i] << "] ";
 }

 std::cout << std::endl;

 return 0;
}

编译,执行:

g++ -std=c++11 -O2 -Wall -pedantic -pthread main.cpp && ./a.out

结果:

string object matched
string literal with 1 matches
the matches were: [cu1709]

这样匹配后(表达式:[a-zA-Z]{2}[0-9]{3,4}),就可以把我们需要的合约筛选出来了,然后进行字符串截取即可取到合约品种。

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】C++正则表达式验证期货合约代码

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: