Archive

Posts Tagged ‘class’

Regular expressions in C++ with Glib::Regex

November 30, 2013 No comments

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <glibmm/regex.h>
#include <glibmm/ustring.h>
#include <iostream>

using namespace std;
using namespace Glib;

int main()
{
  Glib::ustring str1 = "Hi %name%, your friend %friend% told me you are a %job%.";
  cout << "Original string: "<< str1 << endl;

  Glib::RefPtr<Regex> myr = Regex::create("%[a-z]*%");
  MatchInfo minfo;

  myr->match(str1, minfo);
  int start, end;
  int i=0;

  while (minfo.matches())
    {
      cout << "Word: " << minfo.fetch(0)<<endl;
      if (minfo.fetch_pos(0, start, end))
        {
          cout << "   Start:  "<<start<<endl<<"   End: "<<end<<endl;
        }
      minfo.next();
      ++i;
    }
    cout << "Occurrences: "<<i<<endl;
}

To compile it, we must have glibmm installed, then:

$ g++ -o regex1 regex1.cpp `pkg-config –libs –cflags glibmm-2.4`

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <glibmm/regex.h>
#include <glibmm/ustring.h>
#include <iostream>

using namespace std;
using namespace Glib;

int main()
{
  Glib::ustring str1 = "Hi %name%, your friend %friend% told me you are a %job%.";
  cout << "Original string: "<< str1 << endl;

  Glib::RefPtr<Regex> myr = Regex::create("%([a-z]*)%");
  MatchInfo minfo;

  myr->match(str1, minfo);
  int start, end;
  int i=0;

  while (minfo.matches())
    {
      cout << "Match "<< i+1 << ": "<<endl;

      for (unsigned j = 0; j< minfo.get_match_count(); ++j)
    {
      cout << "Word ("<<j<<"): " << minfo.fetch(j)<<endl;
      if (minfo.fetch_pos(j, start, end))
        {
          cout << "   Start:  "<<start<<endl<<"   End: "<<end<<endl;
        }
    }
      minfo.next();
      ++i;
    }
    cout << "Occurrences: "<<i<<endl;
}

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:

  • Symbol <
  • a word, letters and numbers
  • maybe a space and several characters, different than < and >
  • Symbol >
  • Several characters. Neither < nor >
  • Symbols < and /
  • The same word found in the beginning
  • Symbol >

Then our text string will be: “Sample text

And the result will be:

Original String: <MyTag id=”123″>Sample text</MyTag>
Match 1:
Word (0): <MyTag id=”123″>Sample Text</MyTag>
Start: 0
End: 51
Word (1): MyTag
Start: 1
End: 6
Word (2): id=”123″
Start: 6
End: 15
Word (3): Sample text
Start: 16
End: 43
Occurrences: 1

(Note: Start and End position, won’t match reality, they were taken by another example)

So, with this little regex we have parsed this XML tag, this would be useful in little projects.

Foto: li xiang (Flickr) CC-by

Know PHP methods visibility (public, protected, private)

October 24, 2013 No comments

When coding in Object Oriented PHP, sometimes we would like to know the visibility of certain methods. For example, we are using an instance of an unknown class in compile-time (or coding time) with its name in a variable just like:

1
2
3
4
5
<?php
  $class = (isset($_GET['class']))?$_GET['class']:false;
  if ($class)
    $myObject = new $class;
?>

So, if we are going to call any method, we should know its visibility first. Another example, could be when we are checking the visibility in a base class. A subclass (“Heir”) of “Base” was instanced, and some methods of Base are going to call methods of Heir, so Base must know if they can be called.

Let’s check the visibility with this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
function methodType($class, $method)
{
  try
    {
      $method = new ReflectionMethod($class, $method);
     
      if ($method->isPrivate())
    return 'private';
      elseif ($method->isProtected())
    return 'protected';
      elseif ($method->isPublic())
    return 'public';
    }
  catch (Exception $e)
    {
      return 'error';
    }
}

class MyClass
{
  function __construct()
  {
  }

  private function myPrivate()
  {
    echo "shhh... this is private\n";
  }

  public function myPublic()
  {
    echo "Hello everybody!!\n";
  }

  protected function myProtected()
  {
    echo "Protected method!!\n";
  }

}

$myclass = new MyClass();

echo 'myPrivate: '.methodType($myclass, 'myPrivate')."\n";
echo 'myPublic: '.methodType($myclass, 'myPublic')."\n";
echo 'myProtected: '.methodType($myclass, 'myProtected')."\n";
echo 'notExists: '.methodType($myclass, 'notExists')."\n";
?>

Here we have methodType() function, giving the class and method, it will return a string “public”, “private”, “protected” or “error”. This function uses ReflectionMethod class from PHP, it can do lots of things more.4

Well, back to the second example, I’d like to record calls of some methods, so I will create a superclass MyClassBase with a invoker method used to call other methods inside the other class only if they are public:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
function methodType($class, $method)
{
  try
    {
      $method = new ReflectionMethod($class, $method);
     
      if ($method->isPrivate())
    return 'private';
      elseif ($method->isProtected())
    return 'protected';
      elseif ($method->isPublic())
    return 'public';
    }
  catch (Exception $e)
    {
      return 'error';
    }
}

class MyClassBase
{
  function __construct()
  {
    echo "Class created\n";
  }
 
  public function invoker($method, $arguments=array())
  {
  try
    {
      $method = new ReflectionMethod($this, $method);
     
      if ($method->isPublic())
    {
      echo "I'm invoking method ".$method->name."...\n";
      return $method->invokeArgs($this, $arguments);
    }
      else
    echo "Method ".$method->name." is not public!!\n";
    }
  catch (Exception $e)
    {
      echo "Error invoking ".$method."\n";
    }
  }
}

class MyClass extends MyClassBase
{
  function __construct()
  {
    echo "Creating MyClass...\n";
  }

  private function myPrivate()
  {
    echo "shhh... this is private\n";
  }

  public function myPublic()
  {
    echo "Hello everybody!!\n";
  }

  public function myPublicCalls()
  {
    echo "I'm a public method that calls private methods...\n";
    $this->myPrivate();
  }

  public function myPublicArguments($arg1, $arg2)
  {
    echo "I'm a public method with two arguments: ".$arg1." and ".$arg2."\n";
  }

  protected function myProtected()
  {
    echo "Protected method!!\n";
  }

}

$myclass = new MyClass();

$myclass->invoker('notExists');
$myclass->invoker('myPrivate');
$myclass->invoker('myPublic');
$myclass->invoker('myPublicCalls');
$myclass->invoker('myPublicArguments', array('argument1', 'argument2'));
?>

The answer will be:

Creating MyClass…
Error invoking notExists
Method myPrivate is not public!!
I’m invoking method myPublic…
Hello everybody!!
I’m invoking method myPublicCalls…
I’m a public method that calls private methods…
shhh… this is private
I’m invoking method myPublicArguments…
I’m a public method with two arguments: argument1 and argument2

In fact, when a private or inexistent method is called, invoker() will give an error, and we can capture it easily, avoiding a PHP error to be triggered, or we can throw an exception. And if the method is public, we can run code before and after calling it, so we can log this call.

Another interesting thing is invoking the method with arguments, these arguments must be specified inside an array, so instead of calling:

1
2
3
<?php
myPublicArguments('argument1', 'argument2');
?>

When using the invoker we must do:

1
2
3
<?php
$myclass->invoker('myPublicArguments', array('argument1', 'argument2'));
?>
Top