Trouble with simple regex

I'm having some trouble getting a caret ( ^ ) to work as the beginning of a line:
http://www.cplusplus.com/reference/regex/ECMAScript/

1
2
3
4
5
6
7
8
std::string str = "{hello";

std::regex exp = "^\\{.*";
std::smatch sm;

std::regex_match( str, sm, exp );

sm.size() == 0; // true 


It works just fine without the caret.
What's your compiler exactly? gcc, infamously, didn't implement regex until 4.9 (so you'd have to use boost if you have an earlier gcc)

Otherwise, your code works (except for the invalid regex initialization)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string str = "{hello";
    std::regex exp("^\\{.*");

    std::smatch sm;
    std::regex_match( str, sm, exp );

    std::cout << "sm.size() = " << sm.size() << '\n'
              << "sm[0] = '" << sm[0] <<  "'\n";
}


see it live: http://coliru.stacked-crooked.com/a/5cc59cff2aab93de
Last edited on
¿is there a way to avoid duplicating the backslash? it's quite confusing.


When you say "^\{.*" it's saying match if the line starts with a open brace (it would take from beginning to end)
without the caret would be "\{.*" match if the line contains an open brace (it would take from the brace to the end)

The difference should be clear with the input "foo{bar}"
with the caret it would fail, without it match "{bar}"


> sm.size() == 0; // true
It would be nice if you provide a test case
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <regex>
int main(){
	std::string str = "{hello";

	std::regex exp{"^\\{.*"}; //explicit constructor
	std::smatch sm;

	std::regex_match( str, sm, exp );

	std::cout << sm.size() << '\n';
}
1
with gcc 4.9.0 and clang 3.4
The "match" function matches the entire string, so ^ and $ don't mean much. You want the "search" function.

Hope this helps.
is there a way to avoid duplicating the backslash?
Yes http://en.cppreference.com/w/cpp/language/string_literal
@Cubbi: I'm using 4.8.2, so judging by your Coliru, I guess it's the compiler. As for C++ lateness to the regex game, I'm surprised regex isn't a core part of C. Looks like 4.9 is available to me, so that is nice.

Thanks for the help
This regex library has been available to C++ programmers as boost.regex since the year 2000, just 2 years after C++ was even standardized.

It then entered C++ as part of the TR1 library extensions spec (released 2007), and then merged into C++11 along with almost all of TR1. It's not C++ that's late, it's gcc.
Topic archived. No new replies allowed.