0

I have to generate regex programatically. In this particular case, my regex object should correspond to the string: "([(+1)((+1))])((-1)(+1))*([(-1)((-1))])"

#include <bits/stdc++.h>
using namespace std;

int main()
{
    regex r("([(<1)((<1))])((<1)(>1))*([(>1)((>1))])");
    cout << (regex_match("<1>1", r) ? "YES" : "NO") << endl;
}

However, I am getting the match as false. Are the parenthesis being treated as matchable characters?

I think I have misunderstood regex syntax somewhere. I could not find any helpful material online having complex regex.

PS: I understand that this is a very clumsy regex for this problem. Any leads towards resources for simplifying regex will also be appreciated.

UPDATE: (updated code) https://ideone.com/8HAuEk

1 Answers1

1

There are at least three issues with your code.

  1. Don't include <bits/stdc++.h>.

  2. You have an unclosed parenthesis in your code (ironically).

    cout << (regex_match("+1-1", r ? "YES" : "NO") << endl;
    //      ^ here
    
  3. If we fix that line:

    cout << (regex_match("+1-1", r) ? "YES" : "NO") << endl;
    

    we get that runtime error you're asking about. It's caused by (+1). (+ is a regex syntax error because + is a quantifier and can't appear at the beginning of a group. If you want to match it literally, it should be "(\\+1)".

Also, [(+1)((+1))] doesn't make much sense. It's equivalent to [()1+] and matches a single character that is either (, ), +, or 1.

melpomene
  • 79,257
  • 6
  • 70
  • 127
  • Thanks for your answer! In point 3, why are parenthesis not be used to group the subregex ? My intent is to have <1 ('+' replaced by < to avoid quantifier clash) in the beginning. – Yash Kumar Bansal Nov 12 '17 at 04:12
  • Equivalently, how do I write regex which accepts only two strings ab and cd. I thought it should be [(ab)(cd)]. But it is not working like that in ideone code. – Yash Kumar Bansal Nov 12 '17 at 04:16