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

Edu*_*aki 0 c c# c++

我在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();
Run Code Online (Sandbox Code Playgroud)

...我试图用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(); 
    }
Run Code Online (Sandbox Code Playgroud)

那么,我怎样才能获得匹配的索引?

jal*_*alf 5

根据您的编译器,<regex>标头可能是可用的,在这种情况下,您只需使用C++ API重写正则表达式,这应该是微不足道的.

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

  • 你看过编译器的头文件了吗?:) (2认同)