Table of Contents

regex example

simple match

#include <string>
#include <iostream>
#include <boost/regex.hpp>
 
int main(int argc, char* argv[]){
 
	std::string input;
	if(argc > 1){
		input = argv[1];
	}else{
		std::cin >> input;
	}
 
	// note that an escape slash \ needs escaped itself
	static const boost::regex email("^([^@]+)@([^@]+)\\.([^.]+)$");
	if( regex_match(input, email) ){
		std::cout << "Matched OK" << std::endl;
	}else{
		std::cout << "No match" << std::endl;
	}
 
	return 0;
}

sub-expression match

A sub-expression match retains the components specified in parethesis () for later use.

#include <string>
#include <iostream>
#include <boost/regex.hpp>
 
int main(int argc, char* argv[]){
 
	std::string input;
	if(argc > 1){
		input = argv[1];
	}else{
		std::cin >> input;
	}
 
	// note that an escape slash \ needs escaped itself
	boost::regex email("^([^@]+)@([^@]+)\\.([^.]+)$");
	boost::cmatch what;
	if( regex_match(input.c_str(), what, email) ){
		std::cout << "Matched OK" << std::endl;
		std::cout << "Account Name: " << what[1] << std::endl;
		std::cout << "Computer Name/Subdomain: " << what[2] << std::endl;
		std::cout << "Domain: " << what[3] << std::endl;
	}else{
		std::cout << "No match" << std::endl;
	}
 
	return 0;
}

compile command

* this command was specific to a particular boost version and my configuration; the static version of the regex library was used

c++ -I/usr/local/include/boost-1_37/ -o boostregex boostregex.cpp /usr/local/lib/libboost_regex-xgcc40-mt.a