How to compare regular expressions in Perl and Python?

This article compares regular expressions in Perl and Python, showing syntax differences and practical examples. Regular expressions are patterns used to match and manipulate strings in both languages.

The key difference is syntax: Perl uses $text =~ /pattern/ while Python uses re.search('pattern', text). Let's explore practical examples comparing both approaches.

Check if a String Contains a Word

Both languages can search for specific words in text, but use different syntax.

Python Example

Python uses the re.search() function to find patterns in strings ?

import re

text = "Hello Tutorialspoint"
match = re.search(r"Tutorial", text)
print(bool(match))
True

Perl Example

Perl uses the =~ operator with pattern delimiters ?

my $txt = "Hello Tutorialspoint";

if ($txt =~ /Tutorial/) {
  print "Found\n";  
} else {
  print "Not found\n";
}
Found

Match Email Address

Email validation demonstrates pattern matching capabilities in both languages.

Python Example

Python uses re.match() to validate patterns from the beginning of a string ?

import re

email = "test@tutorialspoint.com"
match = re.match(r"\w+@\w+\.\w+", email)
print(bool(match))
True

Perl Example

Perl directly applies the pattern using the match operator ?

my $email = "test@tutorialspoint.com";

if ($email =~ /\w+@\w+\.\w+/) {
  print "Valid Email\n";  
} else {
  print "Invalid Email\n";
}
Valid Email

Find All Digits in Text

Extracting multiple matches shows how both languages handle repeated patterns.

Python Example

Python's re.findall() returns a list of all matches ?

import re

txt = "There are 126268 articles and 100+ tutorials."
digits = re.findall(r"\d+", txt)
print(digits)
['126268', '100']

Perl Example

Perl uses the global modifier /g to find all matches ?

my $txt = "There are 126268 articles and 100+ tutorials.";
my @nums = ($txt =~ /\d+/g);
print "@nums\n";
126268 100

Comparison

Feature Python Perl
Module Import import re Built-in (no import)
Pattern Delimiters Strings in quotes: r"pattern" Slashes: /pattern/
String Search re.search(r"word", text) $text =~ /word/
Find All Matches re.findall(r"\d+", text) @matches = ($text =~ /\d+/g)
Case Insensitive re.search(r"word", text, re.IGNORECASE) $text =~ /word/i

Conclusion

Both Perl and Python offer powerful regex capabilities with different syntax approaches. Perl integrates regex directly into the language, while Python requires the re module but provides more explicit function calls.

Updated on: 2026-03-24T19:12:04+05:30

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements