Regular expressions examples

No matter which project I’m working on, I always need regular expressions; not on a daily basis though, but it always comes handy to know how to use them.
The thing is, I also always forget how to use them, so I decided to create this page to remember the ones that helped me out !

Add beginning and closing string delimiter (« ) and a comma to all the words in a list :

search with : ^([A-Z0-9]+)
replace with : "\1",
provided that \1 represents the matching sequence in your regexp software (\n is used in Notepad++, some others may use %n)
Web page that helped me found the information :

Turning a copied pasted array into a an int array

Given this :

0 -1 -2 -3 +3 +2 +1
+1 0 -1 -2 -3 +3 +2
+2 +1 0 -1 -2 -3 +3
+3 +2 +1 0 -1 -2 -3
-3 +3 +2 +1 0 -1 -2
-2 -3 +3 +2 +1 0 -2
-1 -2 -3 +3 +2 +1 0

if you first replace the tabs with commas,
search with : \t
replace with : ,, you get this :


and then using :
search with : (\w)$
replace with : \1},{, you get this :


which is approximately an int[][]

Finding a string

For example, if you want to find the string:
meaning you’re looking for a string beginning with class= and ending with a blank; you can use this regexp :
class[^ ]*
which will find every occurences of « class », followed by every caracters possible but  »  » and then ending with  » « .
I found this regexp reading this (french) discussion :

Search and replace a letter following a word using regexps

Imagine you want to search and replace the 4th letter of all words beginning with « set »
Then, search with set(.)
replace with before\1after
Example : setAbc() would become beforeAafterbc()

Decorate a string using regular expressions

As a java programmer, I want to replace word by private String word;
search with ^(.*)$
replace with private String \1;

Matching a regexp and saving results in a file, using Groovy

Problem : « I want to save all occurences of a regexp in a file »
Sadly, Notepad++ could not help me this time, so I decided to write my own sript to achieve that; I chose Groovy as I knew it provided a nice support for regexp manipulations; and also I thought it would be a nice occasion to try it out !

Groovy isn’t it ? (the value.get(0) is because the match is repeated twice in value)

Sources of inspiration for regular expressions

NotePad++ regexp howto
Wikipedia regular expressions page

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée.

Le temps imparti est dépassé. Merci de saisir de nouveau le CAPTCHA.

Ce site utilise Akismet pour réduire les indésirables. Apprenez comment vos données de commentaires sont traitées.

Open Source, Java, Docker, Continuous Integration, Self hosting