Perl Regular Expression - Perl Tutorial
文章推薦指數: 80 %
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
延伸文章資訊
- 1精簡扼要的Perl 課程講義(六):常規表達式(Regular ...
常規表達式(一) (Regular expression) # (1) 基本樣式比對"=~" 與"!~" # 比對字串,成功傳回true # 失敗傳回false "Hello World" =~...
- 2Perl - Regular Expressions - Tutorialspoint
A regular expression is a string of characters that defines the pattern or patterns you are viewi...
- 3Perl 常用的regexp 規則列表 - 朝陽科技大學
Perl 常用的regexp 規則列表. 我們小時候學中文, 從來就不是從文法學起, 而是聽說讀寫很多例句, 腦中自然歸納出一些(可能自己都說不太上來的) 規則。
- 4Perl | Regex Cheat Sheet - GeeksforGeeks
Regex or Regular Expressions are an important part of Perl Programming. It is used for searching ...
- 5Perl matching operator - GeeksforGeeks