Regex – Regular Expression

A regular expression or regex is a pattern defined by a group of characters to match a certain string. It can help you find patterns in a text or do replacements for specific character sequences.

Here a short of overview of some common regex syntax

.any character
\(escape a special character by using the backslash
[abcd]a range of characters
[a-zA-Z]a range of characters indicated with a dash symbol
[^a-z]deny a set of characters
\dmatch any digit
\Dmatch any non-digit
\nmatch a new line
\tmatch a tab
^startcarret is used to indicate the start of a line
end$dollar sign is used to indicate the end of a line
mar(ch)?? is used to optionally match the part between the brackets
[a-z]+matches 1 .. infinite characters between a and z
[a-z]*matches 0 .. infinite characters between a and z
/d{2}matches 2 digits



Here are some examples of regular expressions. You can follow along by entering the regex and strings on this online regex tester.

IP Addresses

IPv4 addresses are in the range of -> Let’s use as example.

We could use \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}, stating that we want four groups of zero to three digits separated by points.

We could make this simpler by noticing that \d{1,3}\. appears three times in this regex: (\d{1,3}\.){3}\d{1,3}

Notice that this would also match string like 902.242.333.424 (numbers above 255) and 230.001.o2.2 (leading zeros). We could fix that with the following regex:




Match a password with at least one lowercase and one uppercase letter, one digit and one of the special characters $#@ with a length between 6 and 12.



The first four groups of this regex are  positive lookaheads , checking to see if a mandatory digit / character is present.

The last groups matches the actual password.



Suppose you are coding and always have to cast to a String e.g. (String) object.get("somekey").

Next you find out that there is a convenient method getString() which returns a String by itself. You should have noticed this sooner. Nonetheless you don’t wan’t to wast any more time and you will replace all (String) object.get("somekey") by object.getString("somekey").

That’s a good use case for a regular expression.

Use \(String\) (\w+).get\((\".*\")\) to match the current code. And use $1.getString($2) as replacement. The dollar signs are used to reference the group that you match in your first regex.

This will change (String) object.get("somekey") into object.getString("somekey") ,

(String) object.get("otherKey") into object.getString("otherkey") ..

Leave a Reply

Your email address will not be published.