DavidSzczesniak
12/4/2017 - 12:20 PM

Quick intro to regexes

Some simple examples of regular expressions, or regexes.

# In its simplest form
print "It matches\n" if "Hello World" =~ /World/;

# Alternative 
print "It doesn't match\n" if "Hello World" !~ /World/;

# The same but with a variable
my $greeting = "World";
print "It matches\n" if "Hello World" =~ /$greeting/;

# Matching against $_ 
my $_ = "Hello World";
print "It matches\n" if /World/;

# Changing delimiters, the 'm' needs to be there for this to work
"Hello World" =~ m!World!;
"Hello World" =~ m{World};

# Regexes must match the string exactly in order to be true
"Hello World" =~ /world/; # False, case sensitive
"Hello World" =~ /o W/; # True, the ' ' is an ordinary character
"Hello World" =~ /World /; # False, no ' ' at the end

# Perl always matched at the earliest possible point in the string
"That hat is red" =~ /hat/; # Matches 'hat' in 'That'

# Meta characters: {}, [], (), ^, $, ., |, *, +, ?, \
# Those can only be matched by putting a backslash before them
"2+2=4" =~ /2+2/; # Doesn't match
"2+2=4" =~ /2\+2/; # Matches