Matching part of a string using a Perl regular expression

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

The ^ means asserting the start of the string. If you move it to the start you could match Emulex followed by a space and make use of \K to ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam StackOverflowforTeamsismovingtoitsowndomain!Whenthemigrationiscomplete,youwillaccessyourTeamsatstackoverflowteams.com,andtheywillnolongerappearintheleftsidebaronstackoverflow.com. Checkyouremailforupdates. Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams MatchingpartofastringusingaPerlregularexpression AskQuestion Asked 3years,3monthsago Modified 3years,3monthsago Viewed 1ktimes 2 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. Inthevariable$hobbitIhavestoredvalue"EmulexLPe16000". NowIneedaregularexpressiontomatchthe"LPe16000"partofthevalueafter"Emulex". Pleaseignoreanysyntaxerrors,Iamanoviceatperl..! $hobbit="EmulexLPe16000" if($hobbit=~m/Emulex^\w+$/) print"lol"; regexperlsubstring Share Improvethisquestion Follow editedJul8,2019at17:23 zdim 60k44goldbadges5050silverbadges7777bronzebadges askedJul8,2019at15:45 shubhamshubham 14411goldbadge11silverbadge88bronzebadges 1 2 ^means"thebeginningofthestring".ItneedstobebeforeEmulex.Thenyoucanput\w+inacapturinggroup. – 41686d6564standsw.Palestine Jul8,2019at15:47 Addacomment  |  2Answers 2 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 4 The^meansassertingthestartofthestring.IfyoumoveittothestartyoucouldmatchEmulexfollowedbyaspaceandmakeuseof\Ktoforgetwhatwasmatched. Thenmatch1+wordcharacters\w+andasserttheendofthestring$ ^Emulex\K\w+$ Regexdemo|Perldemo Ifyouwanttoprintthematch,yourcodemightlooklike: my$hobbit="EmulexLPe16000"; if($hobbit=~m/^Emulex\K\w+$/){ print$&; } Share Improvethisanswer Follow editedJul8,2019at16:25 answeredJul8,2019at15:48 ThefourthbirdThefourthbird 140k1616goldbadges4646silverbadges6565bronzebadges Addacomment  |  2 \Kismuchbetterwaytodoit,yetthisexpressionmightalsowork: Emulex\s+([A-Z]+[a-z]+[0-9]+) Test usestrict; my$str='EmulexLPe16000'; my$regex=qr/Emulex\s+([A-Z]+[a-z]+[0-9]+)/mp; my$subst='$1'; my$result=$str=~s/$regex/$subst/rg; print$result\n"; Theexpressionisexplainedonthetoprightpanelofthisdemo,ifyouwishtoexplorefurtherormodifyit,andinthislink,youcanwatchhowitwouldmatchagainstsomesampleinputsstepbystep,ifyoulike. Share Improvethisanswer Follow answeredJul8,2019at15:51 EmmaEmma 27k1010goldbadges4141silverbadges6565bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedregexperlsubstringoraskyourownquestion. TheOverflowBlog IntroducingtheOverflowOfflineproject Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499) FeaturedonMeta The2022Community-a-thonhasbegun! Mobileappinfrastructurebeingdecommissioned CollectivesUpdate:RecognizedMembers,Articles,andGitLab The[script]tagisbeingburninated StagingGroundWorkflow:CannedComments Related 396 RegularexpressiontomatchDNShostnameorIPAddress? 1124 Istherearegularexpressiontodetectavalidregularexpression? 3949 HowcanIvalidateanemailaddressusingaregularexpression? 5067 Regularexpressiontomatchalinethatdoesn'tcontainaword 1646 HowdoyouaccessthematchedgroupsinaJavaScriptregularexpression? 1792 Howdoyouuseavariableinaregularexpression? 396 Convertinguserinputstringtoregularexpression 586 HowtodoaregularexpressionreplaceinMySQL? 788 HowcanImatch"anythingupuntilthissequenceofcharacters"inaregularexpression? HotNetworkQuestions Howisitpossibletofiltereitherhighorlowfrequenciesofasinglesinewave? Idealprogramminglanguageforanoperationsresearcher Isthetermשָׁלֹום(peace)inIsaiah53:5usuallymisunderstood? Ndimensionalarrayindexutility WhyareringsnotafavoriteoptioninITnetworks? Minimumrotationtogetthemaximumvalue CanIpublishmythesisonlineandgetpaid? HowcanApophishaveason? Havefundamentalparticlesbeenobserved? EvenandOddkinds WhereisthisparkinMontreal,withautumncolortreesandpond? Boxblurthestring UnderwhatauthoritycantheUSmakefederalreservenoteslegaltender? HowdoIlabelatablelikethis? Isthephrasestill"cuantosañostiene"wheretheageisobviouslylessthanoneyear? WhatisaScrumMastertodowhenmanagementdonotsupportAgileandScrum? Pianochordswithanoctaveinthem 1v1barteringbraingame– seeanyproblems? Changingnumberformatsinstrings DoRSAsignaturesreallyneedpadding? nightbusHelsinkiAirporttoLappeenranta FindingTheveninresistanceforabridgecircuitwithvoltagesource Howdovintagesteelframescomparetomodernones? Mysuperpowersonlyworkatnight,howdoIstopcriminalsfromjustdoingcrimeinthemorningtoavoidme? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?