Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Boost.Regex example 1

 

Boost.Regex example 1 is a example how to use the Boost.Regex library.

 

The example below shows how to define a regular expression for a Dutch zip code, how to check for it and how to search for it.

 

 

 

 

 

 

Operating system: Ubuntu 10.04 LTS Lucid Lynx

IDE: Qt Creator 2.0.0

Project type: Qt4 Console Application

Compiler: G++ 4.4.1

Libraries used:

 

 

 

 

 

Qt project file

 

#-------------------------------------------------
#
# Project created by QtCreator 2010-08-06T15:52:11
#
#-------------------------------------------------
QT += core
QT -= gui
TARGET = CppRegexExample1
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
LIBS += -L/usr/local/lib -lboost_regex
SOURCES += main.cpp

 

 

 

 

 

Source code

 

 

 

 

 

main.cpp

 

#include <cassert>
#include <string>
#include <boost/regex.hpp>

int main()
{
  //Define how a dutch zip code is formatted
  const boost::regex dutch_zip_code("\\d{4}\\s[A-Z]{2}");

  //Check if the regex works properly
  assert(boost::regex_match("1234 AB",dutch_zip_code)==true);
  assert(boost::regex_match("1234 ab",dutch_zip_code)==false);
  assert(boost::regex_match("1234ab",dutch_zip_code)==false);

  //Define a sentence with a Dutch zip code in it
  const std::string s = "My Dutch zip code is 1234 AB.";

  //Show how boost::regex_match and boost::regex_search work
  assert(boost::regex_match(s,dutch_zip_code)==false
    && "the std::string does not match a dutch zip code");
  assert(boost::regex_search(s,dutch_zip_code)==true
    && "but the std::string does contain a dutch zip code");

  //Show how to obtain a Dutch zip code from a std::string
  const boost::sregex_iterator i(s.begin(),s.end(),dutch_zip_code);
  const std::string t = i->str();
  assert(t=="1234 AB");
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict