Python Regular Expressions - Google Developers

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

Python Regular Expressions ... Regular expressions are a powerful language for matching text patterns. This page gives a basic introduction to regular expressions ... Google forEducation Python Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어 Signin Google forEducation Python Guides Overview PythonSetUp PythonIntro Strings Lists Sorting DictsandFiles RegularExpressions Utilities LectureVideos 1.1Introduction,strings1.2Listsandsorting1.3Dictsandfiles2.1Regularexpr2.2Utilities2.3Utilitiesurllib2.4Conclusions PythonExercises BasicExercisesBabyNamesExerciseCopySpecialExerciseLogPuzzleExercise Home Products GoogleforEducation Python PythonRegularExpressions Regularexpressionsareapowerfullanguageformatchingtextpatterns.ThispagegivesabasicintroductiontoregularexpressionsthemselvessufficientforourPythonexercisesandshowshowregularexpressionsworkinPython.ThePython"re"moduleprovidesregularexpressionsupport. InPythonaregularexpressionsearchistypicallywrittenas: match=re.search(pat,str) There.search()methodtakesaregularexpressionpatternandastringandsearchesforthatpatternwithinthestring.Ifthesearchissuccessful,search()returnsamatchobjectorNoneotherwise.Therefore,thesearchisusuallyimmediatelyfollowedbyanif-statementtotestifthesearchsucceeded,asshowninthefollowingexamplewhichsearchesforthepattern'word:'followedbya3letterword(detailsbelow): importre str='anexampleword:cat!!' match=re.search(r'word:\w\w\w',str) #If-statementaftersearch()testsifitsucceeded ifmatch: print('found',match.group())##'foundword:cat' else: print('didnotfind') Thecodematch=re.search(pat,str)storesthesearchresultinavariablenamed"match".Thentheif-statementteststhematch--iftruethesearchsucceededandmatch.group()isthematchingtext(e.g.'word:cat').Otherwiseifthematchisfalse(Nonetobemorespecific),thenthesearchdidnotsucceed,andthereisnomatchingtext. The'r'atthestartofthepatternstringdesignatesapython"raw"stringwhichpassesthroughbackslasheswithoutchangewhichisveryhandyforregularexpressions(Javaneedsthisfeaturebadly!).Irecommendthatyoualwayswritepatternstringswiththe'r'justasahabit. BasicPatterns Thepowerofregularexpressionsisthattheycanspecifypatterns,notjustfixedcharacters.Herearethemostbasicpatternswhichmatchsinglechars: a,X,9,fooandsoon Supposeyouaretryingtomatcheachtagwiththepattern'(<.>)'--whatdoesitmatchfirst? Theresultisalittlesurprising,butthegreedyaspectofthe.*causesittomatchthewhole'fooandsoon'asonebigmatch.Theproblemisthatthe.*goesasfarasisitcan,insteadofstoppingatthefirst>(akaitis"greedy"). Thereisanextensiontoregularexpressionwhereyouadda?attheend,suchas.*?or.+?,changingthemtobenon-greedy.Nowtheystopassoonastheycan.Sothepattern'(<.>)'willgetjust''asthefirstmatch,and''asthesecondmatch,andsoongettingeach<..>pairinturn.Thestyleistypicallythatyouusea.*?,andthenimmediatelyitsrightlookforsomeconcretemarker(>inthiscase)thatforcestheendofthe.*?run. The*?extensionoriginatedinPerl,andregularexpressionsthatincludePerl'sextensionsareknownasPerlCompatibleRegularExpressions--pcre.Pythonincludespcresupport.Manycommandlineutilsetc.haveaflagwheretheyacceptpcrepatterns. Anolderbutwidelyusedtechniquetocodethisideaof"allofthesecharsexceptstoppingatX"usesthesquare-bracketstyle.Fortheaboveyoucouldwritethepattern,butinsteadof.*togetallthechars,use[^>]*whichskipsoverallcharacterswhicharenot>(theleading^"inverts"thesquarebracketset,soitmatchesanycharnotinthebrackets). Substitution(optional) There.sub(pat,replacement,str)functionsearchesforalltheinstancesofpatterninthegivenstring,andreplacesthem.Thereplacementstringcaninclude'\1','\2'whichrefertothetextfromgroup(1),group(2),andsoonfromtheoriginalmatchingtext. Here'sanexamplewhichsearchesforalltheemailaddresses,andchangesthemtokeeptheuser(\1)buthaveyo-yo-dyne.comasthehost. str='[email protected],[email protected]' ##re.sub(pat,replacement,str)--returnsnewstringwithallreplacements, ##\1isgroup(1),\2group(2)inthereplacement print(re.sub(r'([\w\.-]+)@([\w\.-]+)',r'\[email protected]',str)) ##[email protected],[email protected] Exercise Topracticeregularexpressions,seetheBabyNamesExercise. Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2022-06-14UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] Connect Blog Facebook Medium Twitter YouTube Programs WomenTechmakers GoogleDeveloperGroups GoogleDevelopersExperts Accelerators GoogleDeveloperStudentClubs Developerconsoles GoogleAPIConsole GoogleCloudPlatformConsole GooglePlayConsole FirebaseConsole ActionsonGoogleConsole CastSDKDeveloperConsole ChromeWebStoreDashboard Android Chrome Firebase GoogleCloudPlatform Allproducts Terms Privacy SignupfortheGoogleDevelopersnewsletter Subscribe Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어



請為這篇文章評分?