C++ regex Tutorial: Regular Expressions In C++ With Examples

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

A regular expression or regex is an expression containing a sequence of characters that define a particular search pattern that can be used in ... Skiptocontent Menu MENUMENUHomeResourcesFREEeBooksQATesting FreeQATrainingTestCasesSDLCTestLink SoftwareTestingBugZillaMobileTestingJIRA AgileMethodologyDatabaseTestingETLTesting QualityAssuranceTestManagementSAPERPTesting Courses SoftwareTesting(LIVECourse)Selenium(LIVECourse) SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber Automation AutomationTestingSoapUIJIRAAppiumKarateFramework SeleniumQTP/UFTALMQCPostman JMeterLoadRunnerAPITestingRobotFramework TestNGJUnitEclipseMaven TypesOfTesting AllTestingTypesRegressionTestingUnitTestingSmokeTesting FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting LoadTestingStressTestingSecurityTestingPerformanceTesting Tutorials C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest PythonJAVAUNIXSVNAngularJSSpockLaravel SpecFlowJSONFlaskSOAtestMockitoKarma MachineLearningBlockchainGitHubGatlingWiremock Data OraclePL/SQL DataWarehouseExcelVBA BigDataJDBC MongoDB Menu MENUMENUHomeResourcesFREEeBooksQATesting FreeQATrainingTestCasesSDLCTestLink SoftwareTestingBugZillaMobileTestingJIRA AgileMethodologyDatabaseTestingETLTesting QualityAssuranceTestManagementSAPERPTesting Courses SoftwareTesting(LIVECourse)Selenium(LIVECourse) SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber Automation AutomationTestingSoapUIJIRAAppiumKarateFramework SeleniumQTP/UFTALMQCPostman JMeterLoadRunnerAPITestingRobotFramework TestNGJUnitEclipseMaven TypesOfTesting AllTestingTypesRegressionTestingUnitTestingSmokeTesting FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting LoadTestingStressTestingSecurityTestingPerformanceTesting Tutorials C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest PythonJAVAUNIXSVNAngularJSSpockLaravel SpecFlowJSONFlaskSOAtestMockitoKarma MachineLearningBlockchainGitHubGatlingWiremock Data OraclePL/SQL DataWarehouseExcelVBA BigDataJDBC MongoDB LastUpdated:June13,2022 TheTutorialonC++RegularExpressionsorRegexExplainsWorkingofregexinC++includingtheFunctionalityofregexmatch,search,replace,inputvalidationandtokenizing: RegularExpressionorregexesorregexpastheyarecommonlycalledareusedtorepresentaparticularpatternofstringortext.Regexesareoftenusedtodenoteastandardtextualsyntaxofastring. =>VisitHereToSeeTheC++TrainingSeriesForAll. Eachcharacterinaregularexpressioniseitherhavingacharacterwithaliteralmeaningora“metacharacter”thathasspecialmeaning. Forexample,aregularexpression“a[a-z]”canhavevalues‘aa’,‘ab’,’ax’etc.Hereahasaliteralmeaningand[a-z]denotesanylowercasecharacterfromatoz. Ofcourse,theaboveexampleisthesimplestone.Wecanhavearegularexpressionwithmorecomplexpatternstomatch. Almostalltheprogramminglanguagesprovidesupportforregexes.C++hasdirectsupportforregexesfromC++11onwards.Apartfromprogramminglanguages,mostofthetextprocessingprogramslikelexers,advancedtexteditors,etc.useregexes. Inthistutorial,wewillexplorethedetailsofregexesingeneralaswellaswithrespecttoC++programming. WhatYouWillLearn:RegularExpression(regex)InC++RangeSpecificationsRepeatedPatternC++regexExampleFunctionTemplatesUsedInC++regexregex_match()regex_search()regex_replace()C++InputValidationConclusionRecommendedReading RegularExpression(regex)InC++ Aregularexpressionorregexisanexpressioncontainingasequenceofcharactersthatdefineaparticularsearchpatternthatcanbeusedinstringsearchingalgorithms,findorfind/replacealgorithms,etc.Regexesarealsousedforinputvalidation. Mostoftheprogramminglanguagesprovideeitherbuilt-incapabilityforregexorthroughlibraries.FromC++11onwards,C++providesregexsupportbymeansofthestandardlibraryviatheheader. Aregexprocessorthatisusedtoparsearegextranslatesitintoaninternalrepresentationthatisexecutedandmatchedagainstastringthatrepresentsthetextbeingsearched.C++11usesECMAScriptgrammarasthedefaultgrammarforregex.ECMAScriptissimple,yetitprovidespowerfulregexcapabilities. LetusseesomeofthepatternsthatwespecifyinregexlikeRangeSpecification,RepeatedPatterns,etc. RangeSpecifications Specifyingarangeofcharactersorliteralsisoneofthesimplestcriteriausedinaregex. Forexample,wecanspecifyarangeoflowercaselettersfromatozasfollows: [a-z] Thiswillmatchexactlyonelowercasecharacter. Thefollowingcriteria, [A-Za-z0-9] Theaboveexpressionspecifiestherangecontainingonesingleuppercasecharacter,onelowercasecharacterandadigitfrom0to9. Thebrackets([])intheaboveexpressionshaveaspecialmeaningi.e.theyareusedtospecifytherange.Ifyouwanttoincludeabracketaspartofanexpression,thenyouwillneedtoescapeit. Sothefollowingexpression, [\[0-9] Theaboveexpressionindicatesanopeningbracketandadigitintherange0to9asaregex. ButnotethatasweareprogramminginC++,weneedtousetheC++specificescapesequenceasfollows: [\\[0-9] RepeatedPattern Therangeexamplesthatwehavespecifiedabovematchonlyonecharacterorliteral.Ifwewanttomatchmorethanonecharacter,weusuallyspecifythe“expressionmodifier”alongwiththepatterntherebymakingitarepeatedpattern. Anexpressionmodifiercanbe“+”thatsuggestsmatchingtheoccurrenceofapatternoneormoretimesoritcanbe“*”thatsuggestsmatchingtheoccurrenceofapatternzeroormoretimes. ForExample,thefollowingexpression, [a-z]+matchesthestringslikea,aaa,abcd,softwaretestinghelp,etc.Notethatitwillnevermatchablankstring. Theexpression, [a-z]*willmatchablankstringoranyoftheabovestrings. Ifyouwanttospecifyagroupofcharacterstomatchoneormoretimes,thenyoucanusetheparenthesesasfollows: (Xyz)+ TheaboveexpressionwillmatchXyz,XyzXyz,andXyzXyzXyz,etc. C++regexExample ConsideraregularexpressionthatmatchesanMS-DOSfilenameasshownbelow. charregex_filename[]=“[a-zA-Z_][a-zA-Z_0-9]*\\.[a-zA-Z0-9]+”; Theaboveregexcanbeinterpretedasfollows: Matchaletter(lowercaseandthenuppercase)oranunderscore.Thenmatchzeroormorecharacters,inwhicheachmaybealetter,oranunderscoreoradigit.Thenmatchaliteraldot(.).Afterthedot,matchoneormorecharacters,inwhicheachmaybealetterordigitindicatingfileextension. FunctionTemplatesUsedInC++regex Let’snowdiscusssomeoftheimportantfunctiontemplateswhileprogrammingregexinC++. regex_match() Thisfunctiontemplateisusedtomatchthegivenpattern.Thisfunctionreturnstrueifthegivenexpressionmatchesthestring.Otherwise,thefunctionreturnsfalse. FollowingisaC++programmingexamplethatdemonstratestheregex_matchfunction. #include #include #include usingnamespacestd; intmain(){ if(regex_match("softwareTesting",regex("(soft)(.*)"))) cout<matched\n"; constcharmystr[]="SoftwareTestingHelp"; stringstr("software"); regexstr_expr("(soft)(.*)"); if(regex_match(str,str_expr)) cout<matched\n"; if(regex_match(str.begin(),str.end(),str_expr)) cout<matched\n"; cmatchcm; regex_match(mystr,cm,str_expr); smatchsm; regex_match(str,sm,str_expr); regex_match(str.cbegin(),str.cend(),sm,str_expr); cout< #include #include usingnamespacestd; intmain() { //stringtobesearched stringmystr="Shesells_seashellsintheseashore"; //regexexpressionforpatterntobesearched regexregexp("s[a-z_]+"); //flagtypefordeterminingthematchingbehavior(inthiscaseonstringobjects) smatchm; //regex_searchthatsearchespatternregexpinthestringmystr regex_search(mystr,m,regexp); cout< #include #include #include usingnamespacestd; intmain() { stringmystr="ThisissoftwaretestingHelpportal\n"; cout< #include #include usingnamespacestd; intmain() { stringinput; regexinteger_expr("(\\+|-)?[[:digit:]]+"); //Aslongastheinputiscorrectaskforanothernumber while(true) { cout<>input; if(!cin)break; //Exitwhentheuserinputsq if(input=="q") break; if(regex_match(input,integer_expr)) cout<JavaRegularExpressionTutorial  =>CheckALLC++TutorialsHere. RecommendedReading MongoDBRegularExpression$regexwithExample HowtoUseUnixRegularExpressions JavaArrayLengthTutorialWithCodeExamples UnixShellScriptingTutorialwithExamples MongoDBShardingTutorialwithExample SeleniumFindElementByTextTutorialwithExamples UnixPipesTutorial:PipesinUnixProgramming JavaRegexTutorialWithRegularExpressionExamples AboutSoftwareTestingHelpHelpingourcommunitysince2006! MostpopularportalforSoftwareprofessionalswith100million+visitsand300,000+followers!YouwillabsolutelyloveourtutorialsonQATesting,Development,SoftwareToolsandServicesReviewsandmore! RecommendedReading MongoDBRegularExpression$regexwithExample HowtoUseUnixRegularExpressions JavaArrayLengthTutorialWithCodeExamples UnixShellScriptingTutorialwithExamples MongoDBShardingTutorialwithExample SeleniumFindElementByTextTutorialwithExamples UnixPipesTutorial:PipesinUnixProgramming JavaRegexTutorialWithRegularExpressionExamples JOINOurTeam!



請為這篇文章評分?