At work the other day I was creating regular expressions (regexps) in perl for use with swatch. Instead of testing the regexps by entering them into the swatch config file, restart swatch, and use the “logger” command to trigger swatch to take action, I thought I’d simplify it by creating a small script. Since swatch is written i perl, I created a tiny script in perl so that there wouldn’t be any regexps mismatch between how the script interprets regexps and how swatch interprets them.
The script takes as input a text string and a regular expression, and prints the matched regexps (if any). In the example below I pass a simple regexps to the script to extract the hostname from a sample rsyslog entry:
[root@server ~]# perl regexp-test.pl "2011-04-13T12:24:37+02:00 server root: sample text" '\s\w+\s'
Input string: "2011-04-13T12:24:37+02:00 server root: sample text"
Input regexp: "\s\w+\s"
Result: " server "
The script itself looks like this:
# Parse command line arguments
$input_string = $ARGV;
$input_regexp = $ARGV;
print "Input string: \"$input_string\"\n";
print "Input regexp: \"$input_regexp\"\n";
# Search for the regexp. The parenthesis makes perl put the
# matched pattern (if any) into the special variable $1
$input_string =~ m/($input_regexp)/;
print "Result: \"$1\"\n";