Perl | Regex Cheat Sheet - GeeksforGeeks
文章推薦指數: 80 %
Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPerl|SearchinginaFileusingregexPerl|RegularExpressionsPerl|OperatorsinRegularExpressionPerl|RegexCharacterClassesPerl|QuantifiersinRegularExpressionPerl|SpecialCharacterClassesinRegularExpressionsPerl|RegexCheatSheetPerl|substitutionOperatorPerl|Loops(for,foreach,while,do…while,until,Nestedloops)Perl|DecisionMaking(if,if-else,Nested–if,if-elsifladder,unless,unless-else,unless-elsif)Perl|split()FunctionPerl|chomp()FunctionPerl|chop()FunctionPerl|Removingleadingandtrailingwhitespaces(trim)Perl|StringOperatorsPerl|Stringfunctions(length,lc,uc,index,rindex)Perl|UsefulStringfunctionsPerl|UsefulArrayfunctionsPerl|exists()FunctionPerl|grep()FunctionPerl|push()FunctionPerl|substr()functionPerl|PolymorphisminOOPsPerl|Arrays(push,pop,shift,unshift)Perl|SearchinginaFileusingregexPerl|RegularExpressionsPerl|OperatorsinRegularExpressionPerl|RegexCharacterClassesPerl|QuantifiersinRegularExpressionPerl|SpecialCharacterClassesinRegularExpressionsPerl|RegexCheatSheetPerl|substitutionOperatorPerl|Loops(for,foreach,while,do…while,until,Nestedloops)Perl|DecisionMaking(if,if-else,Nested–if,if-elsifladder,unless,unless-else,unless-elsif)Perl|split()FunctionPerl|chomp()FunctionPerl|chop()FunctionPerl|Removingleadingandtrailingwhitespaces(trim)Perl|StringOperatorsPerl|Stringfunctions(length,lc,uc,index,rindex)Perl|UsefulStringfunctionsPerl|UsefulArrayfunctionsPerl|exists()FunctionPerl|grep()FunctionPerl|push()FunctionPerl|substr()functionPerl|PolymorphisminOOPsPerl|Arrays(push,pop,shift,unshift)Perl|RegexCheatSheetViewDiscussion ImproveArticle SaveArticle LikeArticle LastUpdated: 31Jul,2019RegexorRegularExpressionsareanimportantpartofPerlProgramming.Itisusedforsearchingthespecifiedtextpattern.Inthis,setofcharacterstogetherformthesearchpattern.Itisalsoknownasregexp.Whenuserlearnsregularexpressionthentheremightbeaneedforquicklookofthoseconceptswhichhedidn’tuseoften.Sotoprovidethatfacility,aregexcheatsheetiscreatedwhichcontainsthedifferentclasses,Characters,modifiersetc.whichareusedinregularexpression.CharacterClassesCharacterclassesareusedtomatchthestringofcharacters.Theseclasseslettheusermatchanyrangeofcharacters,whichuserdon’tknowinadvance.ClassesExplanation[abc.]Itincludesonlyoneofspecifiedcharactersi.e.‘a’,‘b’,‘c’,or‘.’[a-j]Itincludesallthecharactersfromatoj.[a-z]Itincludesalllowercasecharactersfromatoz.[^az]Itincludesallcharactersexceptaandz.\wItincludesallcharacterslike[a-z,A-Z,0-9]\dItmatchesforthedigitslike[0-9][ab][^cde]Itmatchesthatthecharactersaandbshouldnotbefollowedbyc,dande.\sItmatchesfor[\f\t\n\r]i.eformfeed,tab,newlineandcarriagereturn.\WComplementof\w\DComplementof\d\SComplementof\sExample:#Perlprogramtodemonstrate#characterclass #ActualString$str="45char"; #Printsmatchfoundif #itsfoundin$str#byusing\wif($str=~/[\w]/){ print"MatchFound\n";} #Printsmatchnotfound #ifitisnotfoundin$strelse{ print"MatchNotFound\n";}Output:MatchFoundAnchorsAnchorsdonotmatchanycharacteratall.Instead,theymatchaparticularpositionasbefore,after,orbetweenthecharacters.AnchorsExplanation^Itmatchesatthebeginningofthestring.$Itmatchesattheendofthestring.\bItmatchesatthewordboundaryofthestringfrom\wto\W.\AItmatchesatthebeginningofthestring.\ZItmatchesattheendingofthestringorbeforethenewline.\zItmatchesonlyattheendofthestring.\GItmatchesatthespecifiedpositionpos().\p{….}UnicodecharacterclasslikeIsLower,IsAlphaetc.\P{….}ComplementofUnicodecharacterclass[:class:]POSIXCharacterClasseslikedigit,lower,asciietc.Example:#Perlprogramtodemonstrate#useofanchorsinregex #ActualString$str="55"; #Printsmatchfoundif #itsfoundin$str#usingAnchors/ if($str=~/[[:alpha:]]/){ print"MatchFound\n";} #Printsmatchnotfound #ifitisnotfoundin$strelse{ print"MatchNotFound\n";}Output:MatchNotFoundMetaCharactersMetacharactersareusedtomatchpatternsinPerlregularexpressions.Allthemetacharactersmustbeescaped.CharactersExplanation^Tocheckthebeginningofthestring.$Tochecktheendingofthestring..Anycharacterexceptnewline.*Matches0ormoretimes.+Matches1ormoretimes.?Matches0ormoretimes.()Usedforgrouping.\Useforquoteorspecialcharacters.[]Usedforsetofcharacters.{}Usedasrepetitionmodifier.QuantifiersTheseareusedtocheckforthespecialcharacters.Therearethreetypesofquantifiers‘?’Itmatchesfor0or1occurrenceofcharacter.‘+’Itmatchesfor1ormoreoccurrenceofcharacter.‘*’Itmatchesfor0ormoreoccurrenceofcharacter.UsingQuantifiersExplanationa?Itchecksif‘a’occurs0or1time.a+Itchecksif‘a’occurs1ormoretimea*Itchecksif‘a’occurs0ormoretimea{2,6}Itchecksif‘a’occurs2to6timesa{2,}Itchecksif‘a’occurs2toinfinitetimesa{2}Itchecksif‘a’occurs2time.Example:#Perlprogramtodemonstrate#useofquantifiersinregex #ActualString$str="color"; #Printsmatchfoundif #itsfoundin$str#usingquantifier?if($str=~/colou?r/){ print"MatchFound\n";} #Printsmatchnotfound #ifitisnotfoundin$strelse{ print"MatchNotFound\n";}Output:MatchFoundModifiersModifiersExplanation\gItisusedtoreplacealltheoccurrenceofstring.\gcItallowscontinuedsearchafter\gmatchfails.\sIttreatsstringasasingleline.iItturnsoffthecasesensitivity.\xItdisregardallthewhitespaces.(?#text)Itisusedtoaddcommentinthecode.(?:pattern)Itisusedtomatchpatternofthenoncapturinggroup.(?|pattern)Itisusedtomatchpatternofthebranchtest.(?=pattern)Itisusedforpositivelookaheadassertion.(?!pattern)Itisusedfornegativelookaheadassertion.(<=pattern)Itisusedforpositivelookbehindassertion.(
延伸文章資訊
- 1精簡扼要的Perl 課程講義(六):常規表達式(Regular ...
常規表達式(一) (Regular expression) # (1) 基本樣式比對"=~" 與"!~" # 比對字串,成功傳回true # 失敗傳回false "Hello World" =~...
- 2Perl | Regular Expressions - GeeksforGeeks
- 3Regular expression - Wikipedia
- 4perlre - Perl regular expressions - Perldoc Browser
DESCRIPTION. This page describes the syntax of regular expressions in Perl. If you haven't used r...
- 5Perl - Regular Expressions - Tutorialspoint