MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

Perl & Python: Regex Example

Xah Lee, ,

Python

Here's a simple example of using regex to replace text.

#-*- coding: utf-8 -*-
# python

# simple example of using regex to replace text

import re

myText = "123123";

newText = re.sub(r"2", r"8", myText)

print newText; # 183183

Here's a more complex example, replacing all “gif” image paths to “png” in HTML file.

# -*- coding: utf-8 -*-
# python

import re

myText = r"""<p><img src="./rabbits.gif" width="30" height="20">
and <img class="xyz" src="../cats.gif">,
but <img src ="tigers.gif">,
 <img src=
"bird.gif">!</p>"""

newText = re.sub(r'src\s*=\s*"([^"]+)\.gif"', r'src="\1.png"', myText)

print newText

See also: Python Regex Documentation: String Pattern Matching.

Perl

Here's a simple example of using regex to replace text.

#-*- coding: utf-8 -*-
# perl

$text = "123123";
$text =~ s/2/8/g; # g is a flag for global. meaning replace all occurances
print $text; # 183183

If all you want is to test a match instead of replace, do like this: $text =~ m/regexPatternHere/. If there is a match, it returns true.

Here's a more complex example, replacing all “gif” image paths to “png” in HTML file.

# -*- coding: utf-8 -*-
# perl

$myText = qq[<p><img src="./rabbits.gif" width="30" height="20">
and <img class="xyz" src="../cats.gif">,
but <img src ="tigers.gif">,
 <img src=
"bird.gif">!</p>];

$myText =~ s/src\s*=\s*"([^"]+)\.gif"/src="\1.png"/g;  # replacement on $myText

print $myText;
blog comments powered by Disqus