SlideShare a Scribd company logo
1 of 16
BY
SANA MATEEN
INTRODUCTION TO REGULAR EXPRESSIONS
 It is a way of defining patterns.
 A notation for describing the strings produced by regular expression.
 The first application of regular expressions in computer system was in the text
editors ed and sed in the UNIX system.
 Perl provides very powerful and dynamic string manipulation based on the usage of
regular expressions.
 Pattern Match – searching for a specified pattern within string.
 For example:
 A sequence motif,
 Accession number of a sequence,
 Parse HTML,
 Validating user input.
 Regular Expression (regex) – how to make a pattern match.
HOW REGEX WORK
Regex
code
Perl
compiler
Input data (e.g. sequence file)
outputregex engine
Simple Patterns
 Place the regex between a pair of forward slashes ( / / ).
 try:
 #!/usr/bin/perl
 while (<STDIN>) {
 if (/abc/) {
 print “>> found ‘abc’ in $_n”;
 }
 }
 Save then run the program. Type something on the terminal then press return.
Ctrl+C to exit script.
 If you type anything containing ‘abc’ the print statement is returned.
STAGES
1. The characters
 | ( ) [ { ^ $ * + ? .
are meta characters with special meanings in regular expression. To
use metacharacters in regular expression without a special meaning being
attached, it must be escaped with a backslash. ] and } are also
metacharacters in some circumstances.
2. Apart from meta characters any single character in a regular expression
/cat/ matches the string cat.
3. The meta characters ^ and $ act as anchors:
^ -- matches the start of the line
$ -- matches the end of the line.
so regex /^cat/ matches the string cat only if it appears at the start of
the line.
/cat$/ matches only at the end of the line.
/^cat$/ matches the line which contains the string cat and /^$/
matches an empty line.
4. The meta character dot (.) matches any single character except
newline, so/c.t/ matches cat,cot,cut, etc.
STAGES
5. A character class is set of characters enclosed in square brackets. Matches any
single character from those listed.
So /[aeiou]/- matches any vowel
/[0123456789]/-matches any digit
Or /[0-9]/
6. A character class of the form /[^....]/ matches any characters except those listed,
so /[^0-9]/ matches any non digit.
7. To remove the special meaning of minus to specify regular expression to match
arithmetic operators.
/[+-*/]/
8. Repetition of characters in regular expression can be specified by the
quantifiers
* -- zero or more occurrences
+ -- one or more occurrences
? – zero or more occurrences
9. Thus /[0-9]+/ matches an unsigned decimal number and /a.*b/ matches a substring
starting with ‘a’ and ending with ‘b’, with an indefinite number of other characters
in between.
FACILITIES
1. Alternations |
If RE1,RE2,RE3 are regular expressions, RE1|RE2|RE3 will match any one of the
components.
2. Grouping- ( )
Round Brackets can be used to group items.
/pitt the (elder|younger)/
3. Repetition counts
Explicit repetition counts can be added to a component of regular expression
/(wet[]){2}wet/ matches ‘ wet wet wet’
Full list of possible count modifiers are
{n} – must occur exactly n times
{n,} –must occur at least n times
{n,m}- must occur at least n times but no more than m times.
4. Regular expression
 Simple regex to check for an IP address:
 ^(?:[0-9]{1,3}.){3}[0-9]{1,3}$
FACILITIES
5. Non-greedy matching
A pattern including
.* matches the longest string it can find.
The pattern .*? Can be used when the shortest match is required.
? – shortest match
6.Short hand
This notation is given for frequent occurring character classes.
d – matches- digit
w – matches – word
s- matches- whitespace
D- matches any non digit character
Capitalization of notation reverses the sense
7. Anchors
b – word boundary
B – not a word boundary
/bJohn/ -matches both the target string John and Johnathan.
8. Back References
Round brackets define a series of partial matches that are remembered for use in subsequent processing or
in the RegEx itself.
9. The Match Operator
The match operator, m//, is used to match a string or statement to a regular expression. For example, to match
the character sequence "foo" against the scalar $bar, you might use a statement like this:
if ($bar =~ /foo/)
Note that the entire match expression.that is the expression on the left of =~ or !~ and the match operator,
returns true (in a scalar context) if the expression matches. Therefore the statement:
$true = ($foo =~ m/foo/);
BINDING OPERATOR
 Previous example matched against $_
 Want to match against a scalar variable?
 Binding Operator “=~” matches pattern on right against string on left.
 Usually add the m operator – clarity of code.
 $string =~ m/pattern/
MATCHING ONLY ONCE
 There is also a simpler version of the match operator - the ?PATTERN?
operator.
 This is basically identical to the m// operator except that it only matches once
within the string you are searching between each call to reset.
 For example, you can use this to get the first and last elements within a list:
 To remember which portion of string matched we use $1,$2,$3 etc
 #!/usr/bin/perl
 @list = qw/food foosball subeo footnote terfoot canic footbrdige/;
 foreach (@list) {
 $first = $1 if ?(foo.*)?; $last = $1 if /(foo.*)/;
 }
 print "First: $first, Last: $lastn";
 This will produce following result First: food, Last: footbrdige
s/PATTERN/REPLACEMENT/;
$string =~ s/dog/cat/;
#/user/bin/perl
$string = 'The cat sat on the mat';
$string =~ s/cat/dog/;
print "Final Result is $stringn";
This will produce following result
The dog sat on the mat
THE SUBSTITUTION OPERATOR
The substitution operator, s///, is really just an extension of the match operator that allows you to
replace the text matched with some new text. The basic form of the operator is:
The PATTERN is the regular expression for the text that we are looking for. The
REPLACEMENT is a specification for the text or regular expression that we want to use to
replace the found text with.
For example, we can replace all occurrences of .dog. with .cat. Using
Another example:
PATTERN MATCHING MODIFIERS
 m//i – Ignore case when pattern matching.
 m//g – Helps to count all occurrence of substring.
$count=0;
while($target =~ m/$substring/g) {
$count++
}
 m//m – treat a target string containing newline characters as multiple
lines.
 m//s –Treat a target string containing new line characters as single string, i.e
dot matches any character including newline.
 m//x – Ignore whitespace characters in the regular expression unless
they occur in character class.
 m//o – Compile regular expressions once only
THE TRANSLATION OPERATOR
 Translation is similar, but not identical, to the principles of substitution, but
unlike substitution, translation (or transliteration) does not use regular
expressions for its search on replacement values. The translation operators
are −
 tr/SEARCHLIST/REPLACEMENTLIST/cds
y/SEARCHLIST/REPLACEMENTLIST/cds
 The translation replaces all occurrences of the characters in SEARCHLIST
with the corresponding characters in REPLACEMENTLIST.
 For example, using the "The cat sat on the mat." string
 #/user/bin/perl
 $string = 'The cat sat on the mat';
 $string =~ tr/a/o/;
 print "$stringn";
 When above program is executed, it produces the following result −
 The cot sot on the mot.
TRANSLATION OPERATOR MODIFIERS
 Standard Perl ranges can also be used, allowing you to specify ranges of characters
either by letter or numerical value.
 To change the case of the string, you might use the following syntax in place of
the uc function.
 $string =~ tr/a-z/A-Z/;
 Following is the list of operators related to translation.
Modifier Description
c Complements SEARCHLIST
d Deletes found but unreplaced
characters
s Squashes duplicate replaced
characters.
SPLIT
 Syntax of split
 split REGEX, STRING will split the STRING at every match of the REGEX.
 split REGEX, STRING, LIMIT where LIMIT is a positive number. This will
split the STRING at every match of the REGEX, but will stop after it found LIMIT-
1 matches. So the number of elements it returns will be LIMIT or less.
 split REGEX - If STRING is not given, splitting the content of $_, the default
variable of Perl at every match of the REGEX.
 split without any parameter will split the content of $_ using /s+/ as REGEX.
 Simple cases
 split returns a list of strings:
 use Data::Dumper qw(Dumper); # used to dump out the contents of any
variable during the running of a program
 my $str = "ab cd ef gh ij";
 my @words = split / /, $str;
 print Dumper @words;
 The output is:
 $VAR1 = [ 'ab', 'cd', 'ef', 'gh', 'ij' ];
Unit 1-strings,patterns and regular expressions

More Related Content

What's hot (20)

Transcriptome analysis
Transcriptome analysisTranscriptome analysis
Transcriptome analysis
 
De novo genome assembly - T.Seemann - IMB winter school 2016 - brisbane, au ...
De novo genome assembly  - T.Seemann - IMB winter school 2016 - brisbane, au ...De novo genome assembly  - T.Seemann - IMB winter school 2016 - brisbane, au ...
De novo genome assembly - T.Seemann - IMB winter school 2016 - brisbane, au ...
 
Vector Engineering.pptx
Vector Engineering.pptxVector Engineering.pptx
Vector Engineering.pptx
 
Perl
PerlPerl
Perl
 
Perl
PerlPerl
Perl
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
Comparative genomics
Comparative genomicsComparative genomics
Comparative genomics
 
Microsatellite
MicrosatelliteMicrosatellite
Microsatellite
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Express sequence tags
Express sequence tagsExpress sequence tags
Express sequence tags
 
Sequence assembly
Sequence assemblySequence assembly
Sequence assembly
 
PRESENTATION MULTIPLE SEQUENCE ALIGNMENT.pptx
PRESENTATION MULTIPLE SEQUENCE ALIGNMENT.pptxPRESENTATION MULTIPLE SEQUENCE ALIGNMENT.pptx
PRESENTATION MULTIPLE SEQUENCE ALIGNMENT.pptx
 
Genome analysis
Genome analysisGenome analysis
Genome analysis
 
Genome assembly
Genome assemblyGenome assembly
Genome assembly
 
sequence alignment
sequence alignmentsequence alignment
sequence alignment
 
Gene mapping
Gene mappingGene mapping
Gene mapping
 
PPT ON ALGORITHM
PPT ON ALGORITHMPPT ON ALGORITHM
PPT ON ALGORITHM
 
Third Generation Sequencing
Third Generation Sequencing Third Generation Sequencing
Third Generation Sequencing
 
Overview of Genome Assembly Algorithms
Overview of Genome Assembly AlgorithmsOverview of Genome Assembly Algorithms
Overview of Genome Assembly Algorithms
 
PPT ON ALGORITHM
PPT ON ALGORITHMPPT ON ALGORITHM
PPT ON ALGORITHM
 

Viewers also liked

Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perlsana mateen
 
Unit 1-perl names values and variables
Unit 1-perl names values and variablesUnit 1-perl names values and variables
Unit 1-perl names values and variablessana mateen
 
Unit 1-subroutines in perl
Unit 1-subroutines in perlUnit 1-subroutines in perl
Unit 1-subroutines in perlsana mateen
 
Unit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuresUnit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuressana mateen
 
Unit 1-uses for scripting languages,web scripting
Unit 1-uses for scripting languages,web scriptingUnit 1-uses for scripting languages,web scripting
Unit 1-uses for scripting languages,web scriptingsana mateen
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashessana mateen
 
Unit 1-introduction to scripts
Unit 1-introduction to scriptsUnit 1-introduction to scripts
Unit 1-introduction to scriptssana mateen
 

Viewers also liked (7)

Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
 
Unit 1-perl names values and variables
Unit 1-perl names values and variablesUnit 1-perl names values and variables
Unit 1-perl names values and variables
 
Unit 1-subroutines in perl
Unit 1-subroutines in perlUnit 1-subroutines in perl
Unit 1-subroutines in perl
 
Unit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuresUnit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structures
 
Unit 1-uses for scripting languages,web scripting
Unit 1-uses for scripting languages,web scriptingUnit 1-uses for scripting languages,web scripting
Unit 1-uses for scripting languages,web scripting
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
 
Unit 1-introduction to scripts
Unit 1-introduction to scriptsUnit 1-introduction to scripts
Unit 1-introduction to scripts
 

Similar to Unit 1-strings,patterns and regular expressions

Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionProf. Wim Van Criekinge
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20Max Kleiner
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressionsKrishna Nanda
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptxDurgaNayak4
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaj Gupta
 
Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)FrescatiStory
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
PERL Regular Expression
PERL Regular ExpressionPERL Regular Expression
PERL Regular ExpressionBinsent Ribera
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaghu nath
 
Introduction to regular expressions
Introduction to regular expressionsIntroduction to regular expressions
Introduction to regular expressionsBen Brumfield
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular ExpressionsMukesh Tekwani
 
Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variablesKing Hom
 

Similar to Unit 1-strings,patterns and regular expressions (20)

Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
Perl_Part4
Perl_Part4Perl_Part4
Perl_Part4
 
Awk essentials
Awk essentialsAwk essentials
Awk essentials
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
newperl5
newperl5newperl5
newperl5
 
newperl5
newperl5newperl5
newperl5
 
Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
PERL Regular Expression
PERL Regular ExpressionPERL Regular Expression
PERL Regular Expression
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Introduction to regular expressions
Introduction to regular expressionsIntroduction to regular expressions
Introduction to regular expressions
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variables
 

More from sana mateen

PHP Variables and scopes
PHP Variables and scopesPHP Variables and scopes
PHP Variables and scopessana mateen
 
Php and web forms
Php and web formsPhp and web forms
Php and web formssana mateen
 
Encryption in php
Encryption in phpEncryption in php
Encryption in phpsana mateen
 
Authentication methods
Authentication methodsAuthentication methods
Authentication methodssana mateen
 
Uses for scripting languages,web scripting in perl
Uses for scripting languages,web scripting in perlUses for scripting languages,web scripting in perl
Uses for scripting languages,web scripting in perlsana mateen
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perlsana mateen
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perlsana mateen
 
Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variablessana mateen
 

More from sana mateen (20)

Files
FilesFiles
Files
 
PHP Variables and scopes
PHP Variables and scopesPHP Variables and scopes
PHP Variables and scopes
 
Php intro
Php introPhp intro
Php intro
 
Php and web forms
Php and web formsPhp and web forms
Php and web forms
 
Mail
MailMail
Mail
 
Files in php
Files in phpFiles in php
Files in php
 
File upload php
File upload phpFile upload php
File upload php
 
Regex posix
Regex posixRegex posix
Regex posix
 
Encryption in php
Encryption in phpEncryption in php
Encryption in php
 
Authentication methods
Authentication methodsAuthentication methods
Authentication methods
 
Xml schema
Xml schemaXml schema
Xml schema
 
Xml dtd
Xml dtdXml dtd
Xml dtd
 
Xml dom
Xml domXml dom
Xml dom
 
Xhtml
XhtmlXhtml
Xhtml
 
Intro xml
Intro xmlIntro xml
Intro xml
 
Dom parser
Dom parserDom parser
Dom parser
 
Uses for scripting languages,web scripting in perl
Uses for scripting languages,web scripting in perlUses for scripting languages,web scripting in perl
Uses for scripting languages,web scripting in perl
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perl
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variables
 

Recently uploaded

scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...HenryBriggs2
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...drmkjayanthikannan
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxSCMS School of Architecture
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksMagic Marks
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptxrouholahahmadi9876
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...jabtakhaidam7
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...vershagrag
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 

Recently uploaded (20)

scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 

Unit 1-strings,patterns and regular expressions

  • 2. INTRODUCTION TO REGULAR EXPRESSIONS  It is a way of defining patterns.  A notation for describing the strings produced by regular expression.  The first application of regular expressions in computer system was in the text editors ed and sed in the UNIX system.  Perl provides very powerful and dynamic string manipulation based on the usage of regular expressions.  Pattern Match – searching for a specified pattern within string.  For example:  A sequence motif,  Accession number of a sequence,  Parse HTML,  Validating user input.  Regular Expression (regex) – how to make a pattern match.
  • 3. HOW REGEX WORK Regex code Perl compiler Input data (e.g. sequence file) outputregex engine
  • 4. Simple Patterns  Place the regex between a pair of forward slashes ( / / ).  try:  #!/usr/bin/perl  while (<STDIN>) {  if (/abc/) {  print “>> found ‘abc’ in $_n”;  }  }  Save then run the program. Type something on the terminal then press return. Ctrl+C to exit script.  If you type anything containing ‘abc’ the print statement is returned.
  • 5. STAGES 1. The characters | ( ) [ { ^ $ * + ? . are meta characters with special meanings in regular expression. To use metacharacters in regular expression without a special meaning being attached, it must be escaped with a backslash. ] and } are also metacharacters in some circumstances. 2. Apart from meta characters any single character in a regular expression /cat/ matches the string cat. 3. The meta characters ^ and $ act as anchors: ^ -- matches the start of the line $ -- matches the end of the line. so regex /^cat/ matches the string cat only if it appears at the start of the line. /cat$/ matches only at the end of the line. /^cat$/ matches the line which contains the string cat and /^$/ matches an empty line. 4. The meta character dot (.) matches any single character except newline, so/c.t/ matches cat,cot,cut, etc.
  • 6. STAGES 5. A character class is set of characters enclosed in square brackets. Matches any single character from those listed. So /[aeiou]/- matches any vowel /[0123456789]/-matches any digit Or /[0-9]/ 6. A character class of the form /[^....]/ matches any characters except those listed, so /[^0-9]/ matches any non digit. 7. To remove the special meaning of minus to specify regular expression to match arithmetic operators. /[+-*/]/ 8. Repetition of characters in regular expression can be specified by the quantifiers * -- zero or more occurrences + -- one or more occurrences ? – zero or more occurrences 9. Thus /[0-9]+/ matches an unsigned decimal number and /a.*b/ matches a substring starting with ‘a’ and ending with ‘b’, with an indefinite number of other characters in between.
  • 7. FACILITIES 1. Alternations | If RE1,RE2,RE3 are regular expressions, RE1|RE2|RE3 will match any one of the components. 2. Grouping- ( ) Round Brackets can be used to group items. /pitt the (elder|younger)/ 3. Repetition counts Explicit repetition counts can be added to a component of regular expression /(wet[]){2}wet/ matches ‘ wet wet wet’ Full list of possible count modifiers are {n} – must occur exactly n times {n,} –must occur at least n times {n,m}- must occur at least n times but no more than m times. 4. Regular expression  Simple regex to check for an IP address:  ^(?:[0-9]{1,3}.){3}[0-9]{1,3}$
  • 8. FACILITIES 5. Non-greedy matching A pattern including .* matches the longest string it can find. The pattern .*? Can be used when the shortest match is required. ? – shortest match 6.Short hand This notation is given for frequent occurring character classes. d – matches- digit w – matches – word s- matches- whitespace D- matches any non digit character Capitalization of notation reverses the sense 7. Anchors b – word boundary B – not a word boundary /bJohn/ -matches both the target string John and Johnathan. 8. Back References Round brackets define a series of partial matches that are remembered for use in subsequent processing or in the RegEx itself. 9. The Match Operator The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence "foo" against the scalar $bar, you might use a statement like this: if ($bar =~ /foo/) Note that the entire match expression.that is the expression on the left of =~ or !~ and the match operator, returns true (in a scalar context) if the expression matches. Therefore the statement: $true = ($foo =~ m/foo/);
  • 9. BINDING OPERATOR  Previous example matched against $_  Want to match against a scalar variable?  Binding Operator “=~” matches pattern on right against string on left.  Usually add the m operator – clarity of code.  $string =~ m/pattern/
  • 10. MATCHING ONLY ONCE  There is also a simpler version of the match operator - the ?PATTERN? operator.  This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset.  For example, you can use this to get the first and last elements within a list:  To remember which portion of string matched we use $1,$2,$3 etc  #!/usr/bin/perl  @list = qw/food foosball subeo footnote terfoot canic footbrdige/;  foreach (@list) {  $first = $1 if ?(foo.*)?; $last = $1 if /(foo.*)/;  }  print "First: $first, Last: $lastn";  This will produce following result First: food, Last: footbrdige
  • 11. s/PATTERN/REPLACEMENT/; $string =~ s/dog/cat/; #/user/bin/perl $string = 'The cat sat on the mat'; $string =~ s/cat/dog/; print "Final Result is $stringn"; This will produce following result The dog sat on the mat THE SUBSTITUTION OPERATOR The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is: The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with. For example, we can replace all occurrences of .dog. with .cat. Using Another example:
  • 12. PATTERN MATCHING MODIFIERS  m//i – Ignore case when pattern matching.  m//g – Helps to count all occurrence of substring. $count=0; while($target =~ m/$substring/g) { $count++ }  m//m – treat a target string containing newline characters as multiple lines.  m//s –Treat a target string containing new line characters as single string, i.e dot matches any character including newline.  m//x – Ignore whitespace characters in the regular expression unless they occur in character class.  m//o – Compile regular expressions once only
  • 13. THE TRANSLATION OPERATOR  Translation is similar, but not identical, to the principles of substitution, but unlike substitution, translation (or transliteration) does not use regular expressions for its search on replacement values. The translation operators are −  tr/SEARCHLIST/REPLACEMENTLIST/cds y/SEARCHLIST/REPLACEMENTLIST/cds  The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding characters in REPLACEMENTLIST.  For example, using the "The cat sat on the mat." string  #/user/bin/perl  $string = 'The cat sat on the mat';  $string =~ tr/a/o/;  print "$stringn";  When above program is executed, it produces the following result −  The cot sot on the mot.
  • 14. TRANSLATION OPERATOR MODIFIERS  Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter or numerical value.  To change the case of the string, you might use the following syntax in place of the uc function.  $string =~ tr/a-z/A-Z/;  Following is the list of operators related to translation. Modifier Description c Complements SEARCHLIST d Deletes found but unreplaced characters s Squashes duplicate replaced characters.
  • 15. SPLIT  Syntax of split  split REGEX, STRING will split the STRING at every match of the REGEX.  split REGEX, STRING, LIMIT where LIMIT is a positive number. This will split the STRING at every match of the REGEX, but will stop after it found LIMIT- 1 matches. So the number of elements it returns will be LIMIT or less.  split REGEX - If STRING is not given, splitting the content of $_, the default variable of Perl at every match of the REGEX.  split without any parameter will split the content of $_ using /s+/ as REGEX.  Simple cases  split returns a list of strings:  use Data::Dumper qw(Dumper); # used to dump out the contents of any variable during the running of a program  my $str = "ab cd ef gh ij";  my @words = split / /, $str;  print Dumper @words;  The output is:  $VAR1 = [ 'ab', 'cd', 'ef', 'gh', 'ij' ];