Find and print the number between the parentheses in C++ using Regex -
i using code find number between parentheses in c++.
i want number extracted out huge file contain these type of data:
successful candidates indicated within paranthesis against roll number , marks given [maximum 5 marks] raise grades in hardship cases indicated plus[+] sign , grace marks cases indicated caret[+] sign 600023[545] 600024[554] 600031[605] 600052[560] *********** grade : d govt. degree boys college, surjani town 600060[877] *********** *********** *********** ***********
///// in 2nd iteration when [554] found. m.size() not reset 0 cause error. how can solve it? how search globally whole file numbers in parenthesis [###]
#include <iostream> #include <fstream> #include <string> #include<conio.h> #include<regex> using namespace std; int main () { ifstream myfile; myfile.open("test.txt") ; if(!myfile) { cout<<"the file entered not present"<<endl; } string str; if(myfile.is_open()) cout<<"file open"; else cout<<"file close"; string output; regex e("\[(\d+)\]"); smatch m; while (!myfile.eof()) { myfile >> str; cout<<"o="<<str<<endl; bool match=regex_search(str,m,e); cout<<"m.size() ="<<m.size()<<endl; int n=0; for( n=0;n<m.size();n++) { cout<<"m["<<n<<"] :str() =" <<m[n].str()<<endl; } } getch(); myfile.close(); return 0; }
update: able read numbers.using string.
but file huge enough visual studio crashes.
i wanted method searches globally in file.
first, should fix regex e("\[(\d+)\]")
regex e("\\[(\\d+)]")
(or regex e(r"(\[(\d+)])")
if c++ environment supports raw string literals).
then, need obtain multiple matches, not capturing group contents doing. use std::sregex_iterator()
, access group 1 contents via m[1].str()
.
see this c++ demo:
std::regex r("\\[(\\d+)]"); std::string s = "successful candidates indicated within paranthesis against roll number , marks given [maximum 5 marks] raise grades in hardship cases indicated plus[+] sign and\ngrace marks cases indicated caret[+] sign\n\n\n600023[545] 600024[554] 600031[605] 600052[560] ***********\n\ngrade : d\ngovt. degree boys college, surjani town\n\n\n600060[877] *********** *********** *********** ***********"; for(std::sregex_iterator = std::sregex_iterator(s.begin(), s.end(), r); != std::sregex_iterator(); ++i) { std::smatch m = *i; std::cout << m[1].str() << '\n'; }
Comments
Post a Comment