1

May we have similar question here stackoverflow:

But my question is:

First I tried to match all x in the string so I write the following code, and it's working well:

string str = line;
regex rx("x");
vector<int> index_matches; // results saved here 
        
for (auto it = std::sregex_iterator(str.begin(), str.end(), rx);
            it != std::sregex_iterator();
            ++it)
{
  index_matches.push_back(it->position());
}

Now if I tried to match all { I tried to replace regex rx("x"); with regex rx("{"); andregex rx("\{");.

So I got an exception and I think it should throw an exception because we use { sometimes to express the regular expression, and it expect to have } in the regex at the end that's why it throw an exception.

So first is my explanation correct?

Second question I need to match all { using the same code above, is that possible to change the regex rx("{"); to something else?

Community
  • 1
  • 1
Hazem Abdullah
  • 1,837
  • 4
  • 23
  • 41

1 Answers1

3

You need to escape characters with special meaning in regular expressions, i.e. use \{ regular expression. But, \ has special meaning in C++ string literals. So, next you need to escape characters with special meaning in C++ string literals, i.e. write:

regex rx("\\{");