Archive

In our programming life, there are some “before and after”s, and one of them is when we learn to use regular expressions… and they are like Twitter, you start with it, follow some famous people and a couple of friends, write a test tweet and a “how wonderful life is” tweet, and forget it. But when it’s your time, you can’t stop using it. So regular expressions or “regex” are the same, when you discover them you say: “Oh! It’s nice!”, or “I could do a lot with it”, but after some time (maybe weeks, months or years), when you have a strings problem, the first solution you try is a regex.

One of the common commands using regex is grep, of course this system is too good to be used only in one place. This is the reason why lots of programming languages have functions or classes to use them easily, for example, PHP had ereg_* in the past, now we use preg_*, in Javascript we use RegExp class, in Java we can even use the String class to parse regex, and so on.

But when working in C++ we don’t have native solutions for that, at least in std, ok C++11 has, but we don’t always have a C++11 compiler ready. We have to use libraries as Boost or Glib to support them, if we don’t want to do it by hand.

We are going to do it with Glib. Imagine we are making a template. Some keywords will be replaced with calculated values. Keywords will begin and end with a %, so we want to get the position of these keywords, and which keyword has been discovered:

In this piece of code, we can see, the regex “%[a-z]*%” has been applied, so we can get lowercase letters from a to z enclosed between % symbols. In the sample string we’ve found 3 occurrences, printing on screen start position, end position and the matched string for each one.

It can be enough for many cases, but this example will return strings like %name% or %friend%, which in certain cases it is not useful, we want name or friend, ok, we can handle that, but we can get those values with regex too applying a parenthesis in the regex, enclosing what we want, this way: “%([a-z]*)%”, in other words, we are interested in this part of the string. But we will obtain several values. One of them will be the old string, the entire match and not only the part we are interested in. But if we change the code a little bit, we’ll be able to get it:

In this case, we are iterating get_match_count() times, so we will get the number of strings returned by each match of the expression (expressions can be so complex, and we can add more parenthesis). Calling minfo.fetch(1) we will get the strings: “name”, “friend” and “job”.

But, to write a better example, let’s parse a simple XML tag. As regex we are taking: “<([\\w:]*)( [^<>]*)?>([^<>]*)</\\1>“, that means: