jan
2
3
Regular Expression Examples
A number of visitors have come to my website using the search terms regex replace. So I thought I would devote an entire article on how to use regular expressions to do a find and replace on a string in some popular languages. Example code is always attractive so lets get to the point! There is example code in Ruby, Perl, Python, Javascript, and Java. [If you have other suggestions let me know or show me in your comments!]
All of the basic examples:
- put the string “one two three” into a variable
- then use a regular expression and a native function to the language to
- transform the original variable’s value to the new string “one 2 three”
Click Here For the Basic Examples
Now you may recognize that in the above examples that regular expressions where not even needed. All we did was find and replace a string and that simple task can be done without regular expressions! So here is a more advanced example without the training wheels.
In the advanced examples:
- the string “a1b2c3″ [may not need to be stored in a variable] is
- manipulated by a [globally replacing] regular expression
- resulting in “a11b22c33″ [where all numbers, but not letters, are duplicated]
- which is stored in a variable
Click Here To Toggle the Advanced Examples
Ruby:
result = 'a1b2c3'.gsub( /(\d)/, '\1\1' )
Perl:
$result = 'a1b2c3';
$result =~ s/(\d)/\1\1/g;
Python:
import re
result =
Javascript:
var result = 'a1b2c3'replace /(\d)/g "$1$1" ;
Java:
Pay strict attention to the number of backslashes required in python, the $1 used in Java and Javascript (however these are also global variables found in Ruby and Perl), and the trailing /g option required in Perl and Javascript for the global replacement. Each language has its own little spin on things.
I hope this helped answer your questions on regular expressions. In case I whet your appetite on Regular Expressions I can point you to my Introductory Article on Regular Expressions and my command line utility rr that allows you to run Ruby regular expression find and replace commands on files, standard input, and even piped input.


Liza on April 24, 2009 at 6:00 am #
I can tell that this is not the first time at all that you write about this topic. Why have you chosen it again?