8.2. Regular Expressions

What are Regular Expressions?

Regular expressions are a means to find and replace regular words like strings, numbers, dates, etc.

What shorthand is to the English language for dictation, regular expressions to normal find and replace. In other words, Regular Expressions are an opinionated find and replace. The possibilities are limitless. Once you have learned shorthand, you would prefer or find an excuse to use it whenever you are writing English. By the same argument, you will many times fall back on Regular Expressions for many activities that you may not even think of.

Scenario: dd/mm/yyyymm/dd/yyyy

Imagine, if you received a text document with all the dates in the current document in the American way of representing dates in the format of mm/dd/yyyy. You have to send this document to your other colleagues/site where they use the representation dd/mm/yyyy. How long do you think it will take for you to replace all the dates? What do you think is the most efficient way to deal with such a situation?

Scenario: Hexadecimal Words

In computers, data is written in binary or Hexadecimal. Binary is written in 0s and 1s, and it has base 2. Decimal is written in base 10 and its digits are from 0 to 9. Hexadecimal is written in base 16, and its digits are from 0 to 9 and A to F. As a computer programmer, imagine you want to quickly write Hexadecimal numbers that can also be read in English, e.g. DEAD. 0xDEAD is a valid Hexadecimal number that can also be read in English. Such examples are FADE, FACE, DEAF, etc.

Now, Imagine you have a list of common dictionary words, and you want to list down all such 4-letter words in Hexadecimal. How fast can you come up with this list?

Scenario: Convert a sequence of numbers to hex for C Array

Imagine you get a log/text file with values. All are in hex. Now, you need to make a C language array from this string.

How would you generate such a log file?

A regular expression can be used to solve such problems. Quite easily, What other option do you have to come up with such a list?