4 Powerful Regex Patterns To Keep Handy In Your Toolbox

Regular Expression or simply Regex is a sequence of characters that defines a search pattern. Regex is highly useful in doing complex look ups and also in performing find and replace queries. Someone who is adept at using Regex patterns can cut down hours of work down to minutes.

In this article, you can learn about 4 very useful and powerful Regex Patterns that you can use to enhance your day-to-day productivity.

Powerful Regex Patterns

1) Regex to add characters to the end of each line

Sometimes you might need to add a semi-colon (“;”) or a comma (“,”) at the end of each line of your code. For this purpose and other similar ones you can use the following technique:

Find: (.)$

This gives you the last character from any given line. Next, add the text you want to append.

Replace: \1\textToReplaceWith

If you do not keep the “1” value, it will replace the last character with your provided text. So, to add something to the end of line use “1“.

2) Regex to find word before a certain character

This is another useful Regex that enables you to find words right before a word or character in your document. If you want to find every word before a certain character like the words that appear right before a comma (“,”) then you can use the regex as follows:

Find: \w+(?=\s*,[^/])

Replace the comma (“,”) with any characters as required.

3) Regex to find word after a certain character

This is similar to the second one but this time you can find the word right after a certain word or character. Similar to finding word/character before a character, you can use the following regex to find the word after certain character:

Find: \?(.*)

This regex finds the words/characters after the first question mark (“?”) in the line.

4) Regex to remove empty lines from a document

The next regex is useful when you are simply removing empty lines or minifying your document. If you have some empty lines in between your document/file that you want to remove, you can use the following simple regex syntax:

Find: \n\r

This will find all the empty lines and you can replace them with blank values. You can also make all the lines to end on a single line using the below regex:

Find: \r\n
  • Leave a Reply