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:

  1. put the string “one two three” into a variable
  2. then use a regular expression and a native function to the language to
  3. 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:

  1. the string “a1b2c3″ [may not need to be stored in a variable] is
  2. manipulated by a [globally replacing] regular expression
  3. resulting in “a11b22c33″ [where all numbers, but not letters, are duplicated]
  4. which is stored in a variable

Click Here For the Advanced Examples

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.


 
 
 

Leave a Reply


Recent Resources

Clicky Web Analytics