I have a few issues with my algorithm, trying to acquire the positions of regex matches in a string.
Please find the code here: https://godbolt.org/z/11q4Mo5fP
1) Why does the regex return 2 matches when there are 3,
2) The expected result is 0:2:4 when it returns 0:0
What I have tried:
Writing the algorithm to derive the expected result.
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::vector<int> mval;
int closed_val = 0;
int open_val = 0;
std::string dup_line = "} } }";
std::smatch m;
std::regex_search(dup_line, m, std::regex("([\\}]+)"));
for (auto mv : m) std::cout << mv << std::endl;
std::cout << m.size() << std::endl;
closed_val = dup_line.find(m[0]);
mval.push_back(closed_val);
try {
if (m.size() >= 1) {
for (int j = 1; j < m.size(); j++) {
std::cout << dup_line << std::endl;
dup_line = dup_line.substr(dup_line.find(m[j]) + 1, dup_line.size() - 1);
std::regex_search(dup_line, m, std::regex("([}]+)"));
std::cout << dup_line << std::endl;
int f = dup_line.find(m[j]);
if (f == -1 || f > dup_line.size() - 1)
continue;
std::cout << f << std::endl;
for (auto mv : m) std::cout << mv << std::endl;
std::cout << dup_line.find(m[j + 1]) << std::endl;
open_val = closed_val + (dup_line.find(m[j + 1]) == -1 ? 0 : dup_line.find(m[j + 1]));
mval.push_back(open_val);
closed_val = open_val;
}
}
}
catch (std::exception& error) {
std::cerr << "error : " << error.what() << std::endl;
}
for (auto mv : mval) std::cout << mv << ":";
std::cout << std::endl;
}
Compiler stderr
<source>: In function 'int main()':
<source>:20:75: warning: comparison of integer expressions of different signedness: 'int' and 'std::__cxx11::match_results<__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> > >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
20 | for (int j = 1; j < m.size(); j++) {
| ~~^~~~~~~~~~
<source>:26:82: warning: comparison of integer expressions of different signedness: 'int' and 'std::__cxx11::basic_string<char>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
26 | if (f == -1 || f > dup_line.size() - 1)
| ~~^~~~~~~~~~~~~~~~~~~~~
<source>:31:114: warning: comparison of integer expressions of different signedness: 'std::__cxx11::basic_string<char>::size_type' {aka 'long unsigned int'} and 'int' [-Wsign-compare]
31 | open_val = closed_val + (dup_line.find(m[j + 1]) == -1 ? 0 : dup_line.find(m[j + 1]));
|
Program returned: 0
Program stdout
}
}
2
} } }
} }
1
}
}
0
0:0: