Regular Expressions Luo Dan 2006-7-26 2017/11/12 1 Regular Expressions Contents Give a simple definiens Give a simple example Basic about perl regex syntax A job to do immediately (a email address: @) Discuss 2017/11/12 2 Regular Expressions Regex-Regular Expressions A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. For Example: *.txt It can be written in Perl, PHP, Java, a .NET language or a multitude of other languages. Here, I only describe regex in Perl. 2017/11/12 3 Regular Expressions A Simple Example #!/bin/perl die ("You don't input a file name!\n") if !defined($ARGV[0]); print ("Warning: without file!\n") if ($ARGV[0] !~ m/\w*/); open (FILE, "<$ARGV[0]") or die ("Cannot open the file!\n"); ***@lines = <FILE>; close(FILE); foreach $input (***@lines) { chomp($input); if ($input =~ m/\w+/) { print ("$input\n"); } } 2017/11/12 4 Regular Expressions Perl's Regular Expression Operators Matching: m//. This operator returns true if PATTERN is found in $_. Ex: m/hello/ Substitution: s///. This operator replaces the sub-string matched by PATTERN with REPLACEMENT. Ex: s/hello/HELLO/ translation. tr///. This operator replaces characters specified by CHARACTERS with the characters in REPLACEMENTS. Ex: tr/ab/c/ The Binding Operators (=~ and !~) 2017/11/12 5 Regular Expressions Option Description g This option finds all occurrences of the pattern in the string. A list of matches is returned or you can iterate over the matches using a loop statement. i This option ignores the case of characters in the string. m This option treats the string as multiple lines. Perl does some optimization by assuming that $_ contains a single line of input. If you know that it contains multiple newline characters, use this option to turn off the optimization. o This piles the pattern only once. You can achieve some small perf