Python Regular Expressions - Google Developers
文章推薦指數: 80 %
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 Русский 中文–简体 日本語 한국어
延伸文章資訊
- 1Python 速查手冊- 12.1 正規運算式re - 程式語言教學誌
本篇文章介紹Python 標準程式庫的re 模組。
- 2re — Regular expression operations — Python 3.10.5 ...
A regular expression (or RE) specifies a set of strings that matches it; the functions in this mo...
- 3Python - Regular Expressions - Tutorialspoint
Python - Regular Expressions ... A regular expression is a special sequence of characters that he...
- 4給自己的Python小筆記— 強大的數據處理工具— 正則表達式
Github完整程式碼連結. “給自己的Python小筆記 — 強大的數據處理工具 — 正則表達式 — Regular Expression — regex詳細教學” is published ...
- 5PYTHON regular expression 實戰 - iT 邦幫忙
regular expression簡稱re,中文:正規表示式. 首先推薦以下網頁學習: Regular Expression介紹中文網頁,而且把符號都說得很清楚!