-
Notifications
You must be signed in to change notification settings - Fork 30
/
escape.pl
52 lines (37 loc) · 1.04 KB
/
escape.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/perl -w
# escape.pl - Automatically escapes regular expressions
use strict;
use Getopt::Std;
# Handle arguments
my %opts;
getopts('h', \%opts);
if ($opts{h}) {
help();
}
# Provide help
sub help {
print "
escape.pl - Automatically escapes regular expressions
Usage: escape.pl
-h
Show this help
Delineate regex commands with three commas, e.g.: ,,,REGEX,,,
and then paste the regex at the prompt.
";
exit;
}
# Ask user for the regex they want to test
print "\nPlease enter the regex: ";
# Clear any spaces at the beginning or end of the input
chomp(my $regex = <STDIN>);
# Split the regex in to an array using a pre-defined delimiter
my @array = split(",,,", $regex);
my $result;
# Loops through the array and on the even array values look for and escape any special characters
for ( my $i=0; $i < scalar(@array); $i++ ) {
if ($i % 2 == 0){
$array[$i] =~ s/(\\|\/|\*|\+|\?|\^|\$|\(|\)|\[|\]|\{|\}|\.|\:|\&|\@|\|)/\\$1/g;
}
$result .= $array[$i];
}
print "\n$result\n\n";