2017-05-07 107 views
0

我想用下面的代码解析位置文件,但是我得到一个奇怪的regex_error,当我调用.what()函数时,它简单地给出了代码5的“regex_error”,我似乎无法找到问题。为什么我的描述少了regex_error?

代码:

std::string line; 
std::ifstream loc_file(argv[1]); 
std::regex line_regex(R"(\S+)\s+([0-9\.]+) ([NS])\s+([0-9\.]+) ([EW])"); 
while (std::getline(loc_file, line)) { 
    std::smatch m; 
    std::regex_search(line, m, line_regex); 
    std::cout << "Location Matches:" << m.length() << std::endl; 
    std::cout << "Loc:" << m[1]; 
    std::cout << " Lat:" << (m[3] == "S") ? -std::stod(m[2]) : std::stod(m[2]); 
    std::cout << " Lon:" << (m[5] == "W") ? -std::stod(m[4]) : std::stod(m[4]) << endl; 
} 

文件格式:

Loc1   0.67408 N 23.47297 E 
Loc2   3.S 23.42157 W 
OtherPlace   3.64530 S 17.47136 W 
SecondPlace   26.13222 N 3.63386 E 

我开发我的正则表达式上regex101.com可以test out my regex there

此外,如果它的事项我使用VS2015

+2

你的原始字符串字面需要括号:'R“(<字符串中的位置>)”' – Galik

+0

@Galik奏效,但为什么有必要吗?我可以在哪里找到关于该文档的文档? –

+1

[字符串文字](http://en.cppreference.com/w/cpp/language/string_literal)#(6) –

回答

0

事实证明,这与我正在使用未转义的Strin有关g文字,需要括号。固定的代码是在这里:

std::string line; 
std::ifstream loc_file(argv[1]); 
std::regex line_regex(R"((\S+)\s+([0-9\.]+) ([NS])\s+([0-9\.]+) ([EW]))"); 
while (std::getline(loc_file, line)) { 
    std::smatch m; 
    std::regex_search(line, m, line_regex); 
    std::cout << "Location Matches:" << m.length() << std::endl; 
    std::cout << "Loc:" << m[1]; 
    std::cout << " Lat:" << (m[3] == "S") ? -std::stod(m[2]) : std::stod(m[2]); 
    std::cout << " Lon:" << (m[5] == "W") ? -std::stod(m[4]) : std::stod(m[4]) << endl; 
} 
相关问题