如何将c#中的正则表达式代码转换为c++

本文关键字:代码 转换 c++ 正则表达式 | 更新日期: 2023-09-27 18:11:40

我在c#中有以下代码:

string data = "something ... 1,000 anything 20,000 other thing...";
string pattern = @"[0-9]+([',|'.][0-9]{1,})*(['.',][0-9]{1,})?";
MatchCollection collection = Regex.Matches(data, pattern);
foreach (Match item in collection)
{
    Console.WriteLine("{0} - {1} - {2}", item.Value, item.Index, item.Length);
}
Console.WriteLine();
Console.WriteLine("End!");
Console.ReadKey();

…我试图转换它在c++(本机代码,没有。net程序集),所以我得到这样的东西:

void main()
    {
        string data = "something ... 1,000 anything 20,000 other thing...";
        regex pattern("([0-9]+(['',|''.][0-9]{1,})*([''.'',][0-9]{1,})?)");

        const sregex_token_iterator end;
        for (sregex_token_iterator i(data.begin(), data.end(), pattern); i != end; ++i)
        {
            std::cout << i->str() << "-" << i->length() << std::endl;
        }
        cout << endl << "End!";
        fflush(stdin); 
        getchar(); 
    }

那么,我如何获得匹配的索引呢?

如何将c#中的正则表达式代码转换为c++

根据您的编译器,<regex>头可能可用,在这种情况下,您可以简单地使用c++ API重写正则表达式,这应该是微不足道的。

如果这是不可用的,<tr1/regex>可能是可用的,或者失败,您可以使用Boost。Regex第三方库

我是这样解决的:

struct MatchInfo
{
    string value;
    int index;
    int length;
};
vector<MatchInfo> DoRegex(string data, string pattern)
{
    regex patternRegex(pattern);
    sregex_token_iterator end;
    vector<MatchInfo> result;
    for (sregex_token_iterator i(data.begin(), data.end(), patternRegex); i != end; ++i)
    {
        MatchInfo item;
        item.index = i->first - data.begin();
        item.length = i->length();
        item.value = i->str();
        result.push_back(item);
    }
    return result;
}