From 367f3c5d63f1a08a059bda3ec9d87ceb008c70db Mon Sep 17 00:00:00 2001 From: Alex <47572179+iArtorias@users.noreply.github.com> Date: Wed, 24 Jan 2024 12:10:43 +0100 Subject: [PATCH] Fix the case for regex when the line could end with the line-break. (#8) * Fix the case when the line could end with the line-break. * Fix the line-break case. Update tests. * Fix the regex typo. --- include/inireader/inireader.hpp | 17 ++++++++++++----- test/test.cpp | 2 ++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/include/inireader/inireader.hpp b/include/inireader/inireader.hpp index afa5711..596d056 100644 --- a/include/inireader/inireader.hpp +++ b/include/inireader/inireader.hpp @@ -39,7 +39,7 @@ namespace ini { std::ifstream ini_file(file); Parse(ini_file); } else { - auto lines = Split(file, '\n'); + auto lines = Split(file); ImplParse(lines); } } @@ -442,21 +442,28 @@ namespace ini { std::string tmp; std::vector lines; while (std::getline(stream, tmp)) { - lines.emplace_back(tmp); + std::smatch match; + + // Check if the line contains a line-break. + // Split it into two lines accordingly. + if (std::regex_match(tmp, match, std::regex(R"((.*)\r(.*))"))) { + lines.emplace_back(match[1].str()); + lines.emplace_back(match[2].str()); + } else + lines.emplace_back(tmp); } return lines; } /** * @param str to split - * @param c to split by * @return a split string inside a vector */ - static std::vector Split(const std::string& str, char c) { + static std::vector Split(const std::string& str) { std::vector res; std::string tmp; for (auto& ch : str) { - if (ch == c) { + if (ch == '\n' || ch == '\r') { res.emplace_back(tmp); tmp.clear(); } else { diff --git a/test/test.cpp b/test/test.cpp index 1eb432e..9a3b606 100644 --- a/test/test.cpp +++ b/test/test.cpp @@ -43,6 +43,7 @@ TEST(Parse, CommentVal) { TEST(Parse, Section1) { auto section = g_testctx->ini_file["Section 1"]; + EXPECT_STREQ(section["test_line_break"].as(), "test1"); EXPECT_STREQ(section["Option 1"].as(), "value 1"); EXPECT_STREQ(section["Option 2"].as(), "value 2"); EXPECT_STREQ(section["oPtion 1"].as(), "value 2\\ \\ \\"); @@ -172,6 +173,7 @@ int main(int argc, char** argv) { "[Section 1]\n" "; comment\n" "# comment2\n" + "test_line_break = test1\r" "Option 1 = value 1 ; option 'Option 1' has value 'value 1'\n" "Option 2 = value 2 # option 'Option 2' has value 'value 2'\n" "oPtion 1 = value 2\\ \\ \\ ; option 'oPtion 1' has value ' value 2 ', 'oPtion 1' and 'Option 1' are different\n"