为什么C 正则只能找到JavaScript Regex在字符串中找到的一部分

why does C++ regex only find a part of what javascript regex find in a string?

本文关键字:字符串 一部分 Regex JavaScript 为什么      更新时间:2023-10-16

我需要在我的代码中使用Regex,但它不应正常工作。我想在每行读取的文件中搜索Test.list.everything,但它仅获得everything。我缩短了代码以使我的问题清楚。在不同的正则测试程序中,我的表达式正常工作,因为您在此测试程序中可以看到它:http://regex101.com/r/ir1ch1。

我使用的输入是

summer1969 2014-03-07 Test.list.everything.1234 123.4.4.34 moreCode

和Regex (([a-zA-Z]+.{0,1})+).[0-9]+

如果我使用std::tr1::regex而不是std::regex,它也无法正常工作。我不知道这两个表达式之间的区别,有什么吗?

C 和我使用的其他程序有什么区别?我如何告诉C 正则表达方式像其他方面一样?

#include <regex>
#include <iostream>
int main()
{
    std::string output = "summer1969 2014-03-07 Test.list.everything.1234 123.4.4.34 moreCode";
    std::cmatch result;
    std::regex rx ("(([a-zA-Z]+\.{0,1})+)\.[0-9]+");
    std::regex_search(output.c_str(), result, rx);
    for(int i = 0; i < result.size(); i++)
    {
        std::cout << i << ". " << result[i] << std::endl;
    }
    system("pause");
    return(0);
}

输出:

0. everything.1234
1. everything
2. everything.

它看起来像是Visual C 2010中的一个错误。如果要捕获文本,则可以使用点和数字,那么您可以使用以下正格版:

"[a-zA-Z\.]+(?=\.\d+)"

它可以正常工作。