Dear all,
I was trying the following code to use regex in c++, but getting an error. Can someone please help me to solve this problem or how to use regex in c++? A sample code for regex in c++. I can easily do this in perl. I also came across many links using Boost library but unable to succeed. I will appreciate your suggestions.
1 #include <iostream>
2 #include <fstream>
3 #include <regex>
4
5 usingnamespace tr1;
6 usingnamespace std;
7
8 int main()
9 {
10 std::string str = "Hello world";
11 std::tr1::regex rx("ello");
12
13 if(regex_match(str.begin(), str.end(), rx))
14 {
15 cout<<"false"<<endl;
16 }
17 else
18 cout<<"true"<<endl;
19 return(0);
20 }
~
~
~
compilation:
g++ reg.cpp -o reg
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.5.1/../../../../include/c++/4.5.1/regex:35:0,
from reg.cpp:3:
/usr/lib/gcc/x86_64-redhat-linux/4.5.1/../../../../include/c++/4.5.1/bits/c++0x_warning.h:31:2: error: #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.
reg.cpp:5:22: error: ‘tr1’ is not a namespace-name
reg.cpp:5:25: error: expected namespace-name before ‘;’ token
reg.cpp: In function ‘int main()’:
reg.cpp:11:6: error: ‘std::tr1’ has not been declared
reg.cpp:11:17: error: expected ‘;’ before ‘rx’
reg.cpp:13:40: error: ‘rx’ was not declared in this scope
reg.cpp:13:42: error: ‘regex_match’ was not declared in this scope
Many thanks for your message, :) Ya I tried everything but it's not working :( can you please paste any working code here, to demonstrate the use of regex in C++, and way to copile it. I have tried everything including boost regex but unable to succeed.
@above: Ya I tried everything and nothing came out of it. Ya I know the error message is explaining the bugs. But dear this forum is not to bet, it is rather to solve other's problems. You could have written some valuable comments. Anyways,, many thanks for your time though :)
1. It's not just a header-only library (you'll have to link with it)
2. regex_match expects to consume all characters of the input string. It looks like you want to use regex_search, instead.
3. If you cannot use boost, you can try POSIX regex (personally, I'd wrap it with RAII and provide a similar API to Boost.Regex).