问题描述
我想提取其他两个字符串之间的子字符串。
例如: /home/toto/FILE_mysymbol_EVENT.DAT
或只是 FILE_othersymbol_EVENT.DAT
我想获得: mysymbol
和 othersymbol
I would like to extract a substring between two others.
ex: /home/toto/FILE_mysymbol_EVENT.DAT
or just FILE_othersymbol_EVENT.DAT
And I would like to get : mysymbol
and othersymbol
我不想使用boost或其他库。只是标准的C ++,除了CERN的ROOT lib,与,但我不' t知道如何使用它...
I don't want to use boost or other libs. Just standard stuffs from C++, except CERN's ROOT lib, with TRegexp, but I don't know how to use it...
推荐答案
从去年开始,C ++有正则表达式嵌入标准。此程序将显示如何使用它们提取您之前的字符串:
Since last year C++ has regular expression built into the standard. This program will show how to use them to extract the string you are after:
#include <regex>
#include <iostream>
int main()
{
const std::string s = "/home/toto/FILE_mysymbol_EVENT.DAT";
std::regex rgx(".*FILE_(\\w+)_EVENT\\.DAT.*");
std::smatch match;
if (std::regex_search(s.begin(), s.end(), match, rgx))
std::cout << "match: " << match[1] << '\n';
}
它会输出:
match: mysymbol
应该注意的是,它不会在GCC中工作库支持正则表达式不是很好。
It should be noted though, that it will not work in GCC as its library support for regular expression is not very good. Works well in VS2010 (and probably VS2012), and should work in clang.
到现在(2016年底)所有现代C ++编译器及其标准库完全符合C ++ 11标准,大多数(如果不是全部)C ++ 14也是如此。 GCC 6和即将到来的Clang 4支持大多数即将推出的C ++ 17标准。
By now (late 2016) all modern C++ compilers and their standard libraries are fully up to date with the C++11 standard, and most if not all of C++14 as well. GCC 6 and the upcoming Clang 4 support most of the coming C++17 standard as well.
这篇关于Regex C ++:提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!