Perl Regular Expression - Perl Tutorial

文章推薦指數: 80 %
投票人數:10人

Summary: in this tutorial, you are going to learn about Perl regular expression, the most powerful feature of the Perl programming language. SkiptocontentHome»PerlRegularExpressionSummary:inthistutorial,youaregoingtolearnaboutPerlregularexpression,themostpowerfulfeatureofthePerlprogramminglanguage.Aregularexpressionisapatternthatprovidesaflexibleandconcisemeanstomatchthestringoftext.Aregularexpressionisalsoreferredtoasregexorregexp.Aregularexpressioncanbeeithersimpleorcomplex,dependingonthepatternyouwanttomatch.BasicmatchingThefollowingillustratesthebasicsyntaxofregularexpressionmatching:string=~regex;Codelanguage:Perl(perl)Theoperator=~isthebindingoperator.Thewholeexpressionreturnsavaluetoindicatewhethertheregularexpressionregexwasabletomatchthestringsuccessfully.Let’stakealookatanexample.First,wedeclareastringvariable:my$s='Perlregularexpressionispowerful';Codelanguage:Perl(perl)Second,tofindifthestring$scontainsthesubstring ulyouusethefollowingregularexpression:$s=~/ul/;Codelanguage:Perl(perl)Puttingitalltogether.#!/usr/bin/perl usewarnings; usestrict; my$s='Perlregularexpressionispowerful'; print"matchfound\n"if($s=~/ul/);Codelanguage:Perl(perl)matchfoundCodelanguage:Perl(perl)Toidentifyifastringdoesnotmatchagivenregularexpression,youusenegatedformofthebindingoperator(!~).Thefollowingexampledemonstrateshowtousethenegationtofindallstringsinanarraythatdoesnotmatchtheregularexpression/er/:#!/usr/bin/perl usewarnings; usestrict; my@words=( 'Perl', 'regularexpression', 'is', 'averypowerul', 'feature' ); foreach(@words){ print("$_\n")if($_!~/er/); }Codelanguage:Perl(perl)Andtheoutputis:regularexpression is featureCodelanguage:Perl(perl)Ifyouwanttomatchapatternthatcontainsaforwardslash(/)character,youhavetoescapeitusingabackslash(\)character.Youcanalsouseadifferentdelimiterifyouprecedetheregularexpressionwiththeletterm,thelettermstandsformatch.Let’stakealookatthefollowingexample:#!/usr/bin/perl usewarnings; usestrict; my@html=( '

', 'htmlfragement', '

', '
', 'Thisisaspan' ); foreach(@html){ print("$_\n")if($_=~m"/"); }Codelanguage:Perl(perl)Howitworks.First,declaredanarrayofstringsthatcontainsHTMLcode.Second,loopedovertheelementsofthearrayanddisplayedtheelementthatcontainsanynumberofforward-slashcharacters(/).Noticethatweprecededthelettermanduseddoublequotesasthedelimiterfortheregularexpression.Thefollowingshowstheoutputoftheprogram: Thisisaspan Pressanykeytocontinue...Codelanguage:HTML,XML(xml)MatchingcaseinsensitivelyLet’stakealookatthefollowingexample:#!/usr/bin/perl usewarnings; usestrict; my$s="Regularexpression"; print"match"if$s=~/Expression/;Codelanguage:Perl(perl)Weexpecttheoutputoftheprogramis“match”.However,itisnot.Becausethestring$sdoesnotcontainthewordExpression,butexpressionwiththefirstletterEinlowercase.ToinstructsPerltomatchapatterncaseinsensitive,youneedtoaddamodifieriasthefollowingexample:#!/usr/bin/perl usewarnings; usestrict; my$s="Regularexpression"; print"match\n"if$s=~/Expression/i;Codelanguage:Perl(perl)Now,wegotwhatweexpected.PerlregularexpressionwithquantifiersInthepreviousexamples,wehavecreatedregularexpressionsbysimplyputtingthecharacterswewanttomatchbetweenapairofslashes.Whatifyouwanttofindthesamesequenceofcharactersmultipletimes?youmayquicklywritesomethinglike:/aaa/Codelanguage:Perl(perl)Howabout100timesormore?Fortunately,regularexpressionengineprovidesyouwithquantifierstobuildsuchkindofpatterns.Forexample,tofindmatch100timesinatext,youcoulddoitasfollows:/a{100}/Codelanguage:Perl(perl)Thefollowingtableprovidessomeusefulquantifiers:QuantifierMeaningA*ZeroormoreAA+OneormoreAA?AisoptionalA{10}TenAA{1,5}FromonetofiveAA{2,}TwoAormoreLet’stakealookatthefollowingexample:#!/usr/bin/perl usewarnings; usestrict; my@words=("available","avatar","avalon"); foreach(@words){ print$_,"\n"if(/a*l+/); }Codelanguage:Perl(perl)Theregularexpression/a*l+/meanszeroormoreafollowedbyatleastoneormorel,therefore,theoutputis:available avalonCodelanguage:Perl(perl)Uptonowyou’venoticedthattheregularexpressionenginetreatssomecharactersinaspecialway.Thesecharactersarecalledmetacharacters.ThefollowingarethemetacharactersinPerlregularexpressions:{}[]()^$.|*+?\Codelanguage:Perl(perl)Tomatchtheliteralversionofthosecharacters,youhavetoabackslash\infrontofthemintheregularexpressions.Inthistutorial,wehaveintroducedyoutosometechniquestomatchstringsoftextusingPerlregularexpressionincludingbasicmatching,case-insensitivematching,andquantifiers.Wasthistutorialhelpful?YesNoPreviouslyPerllastStatementUpNextPerlRegularExpressionCharacterClassesSearchfor:GettingStartedBasicPerlTutorialPerlI/O


請為這篇文章評分?