Skip to content

Commit

Permalink
Fix the case for regex when the line could end with the line-break. (#8)
Browse files Browse the repository at this point in the history
* Fix the case when the line could end with the line-break.

* Fix the line-break case. Update tests.

* Fix the regex typo.
  • Loading branch information
iArtorias authored Jan 24, 2024
1 parent 084fd72 commit 367f3c5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
17 changes: 12 additions & 5 deletions include/inireader/inireader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -442,21 +442,28 @@ namespace ini {
std::string tmp;
std::vector<std::string> 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<std::string> Split(const std::string& str, char c) {
static std::vector<std::string> Split(const std::string& str) {
std::vector<std::string> res;
std::string tmp;
for (auto& ch : str) {
if (ch == c) {
if (ch == '\n' || ch == '\r') {
res.emplace_back(tmp);
tmp.clear();
} else {
Expand Down
2 changes: 2 additions & 0 deletions test/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<const char*>(), "test1");
EXPECT_STREQ(section["Option 1"].as<const char*>(), "value 1");
EXPECT_STREQ(section["Option 2"].as<const char*>(), "value 2");
EXPECT_STREQ(section["oPtion 1"].as<const char*>(), "value 2\\ \\ \\");
Expand Down Expand Up @@ -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"
Expand Down

0 comments on commit 367f3c5

Please sign in to comment.