Tuesday, November 16, 2010

Regular Expressions (RegEx)

This is a very powerful feature of a programming language (although not all programming languages have this feature). Some programmers use it and some are not aware of it (most of my friends don't know this yet). The following is just a simple example/demonstration of using a regex.

Python will be used for the following example.

We have a component naming on the schematic wherein there is a string and number (no spaces in between) e.g. IC1,D1,D3,R1, how do we split the number and the string and display them separately (or put the two splitted fields in two separate variables)?

MyString="IC1"
....... process .....
StringPart="IC"
NumberPart="1"


First Approach using conventional for-loop and if statements.

Using Regular Expression, I can do it this way.

Very short code right?

But python has this comprehension list which can do that as well. Take a look at this short source code using comprehension list.

Lists comprehension is a good way for this as well, but how if the string becomes, [string1][number1][string2][number2] (e.g. IC1D1)? This will be much trickier to extract using conventional methods. Here is the code using regex.

It really takes time and dedication to harness the full power of Regex, but learning it gives us another weapon in our arsenal. :)

No comments:

Post a Comment