0

This program compiles fine without any error but when i run the program it exits unexpectedly saying it ran into some problem .

Analyzing using gdb the program runs into segmentation fault. I dont know much about gdb so can't examine thoroughly if somebody can reproduce the problem and explain the error that will be helpful.

Also what can i do to rectify the problem.

#include<iostream>
#include<regex>
#include<string>
using namespace std;

int main()
{
   bool found;
   cmatch m;
try
{
    found = regex_search("<html>blah blah blah </html>",m,regex("<.*>.* </\\1"));
    cout<< found<<endl<<m.str();
}
catch(exception & e)
{

    cout<<e.what();
}

return 0;


}
Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
rahul tyagi
  • 643
  • 1
  • 7
  • 20

1 Answers1

1

Your back reference needs to refer to a group.

#include<iostream>
#include<regex>
#include<string>
using namespace std;

int main()
{
    bool found;
    cmatch m;
    try
    {
        found = regex_search("<html>blah blah blah </html>",m,regex("<(.*)>(.*)</\\1>"));
        cout << "***whole match***\n";
        cout << "found=" << found << endl;
        cout << m.str() << endl;

        cout << "\n*** parts ***" << endl;
        for (const auto& c : m) {
            cout << c << endl;
        }

    }
    catch(exception & e)
    {

        cout<<e.what() << endl;
    }

    return 0;


}

expected output:

***whole match***
found=1
<html>blah blah blah </html>

*** parts ***
<html>blah blah blah </html>
html
blah blah blah 
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • i get what you are saying but maybe you got the question wrong , the program exits unexpectedly – rahul tyagi Jun 30 '15 at 14:18
  • regex_search has a number of template overloads, depending on how much information you want. The problem you had was that the stdlib wanted to tell you that the regex was invalid (should have thrown an exception). Instead, it crashed. On clang with libc++ your program threw the exception and it was reported on stdout. – Richard Hodges Jun 30 '15 at 14:21
  • your program is same as that of mine except that you traversed through m – rahul tyagi Jun 30 '15 at 14:26
  • @rahultyagi not quite - compare the strings of the regex definitions - mine has round brackets to create the first group inside the opening html tag, which is then referred back to by the back-reference in the closing tag. – Richard Hodges Jun 30 '15 at 14:45
  • ah yes seems like i posted the question in hurry even if i do that it won't run on my machine as the comments to the original question stated but thanks for the answer i appreciate your effort – rahul tyagi Jun 30 '15 at 14:59
  • @rahultyagi ah ok - in that case you'll get better results using boost::regex which is almost identical. – Richard Hodges Jun 30 '15 at 15:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81990/discussion-between-rahul-tyagi-and-richard-hodges). – rahul tyagi Jun 30 '15 at 15:01