I have a Bug at my simple REGEX.
I have been trying to write some simple regular expressions at C++ using std::regex. Here is my code so far.
#include <iostream>
#include <regex>
#include <string>
int main(void)
{
std::string str = "Hello world";
std::regex rx("\w+\s\w+"), rx2("ello");
std::cout << std::boolalpha << std::regex_match(str.begin(), str.end(), rx) << "\n";
std::cout << std::boolalpha << std::regex_search(str.begin(), str.end(), rx2) << "\n";
return 0;
}
This program should print (according to a tutorial)
true
true
but it prints
false
false
Where am I making a mistake? Thanks in advance.
Note: I’m using g++ -std=c++0x %file.cpp% -o %file% if it helps
As already stated g++ (GCC) does not have a proper implementation for regex (it is unimplemented but still compiles).
The Boost library has an implementation for regexes that is almost completely compatible with regexes in C++11. You could use that with minimal changes in your code (just using boost:: instead of std::).
Here is a code that compiles and works:
Note that I have also fixed missing escapes for the backslashes for rx because it does not work without it.
To compile this you have to install libboost-regex-dev package (or something similar if not using Ubuntu/Debian) and execute this: