Python RegEx - W3Schools

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

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified ... Tutorials References Exercises Videos Menu Login Website GetCertified ProNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C C++ C# R React    Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz KotlinQuiz XMLQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop Pro PythonTutorial PythonHOME PythonIntro PythonGetStarted PythonSyntax PythonComments PythonVariables PythonVariables VariableNames AssignMultipleValues OutputVariables GlobalVariables VariableExercises PythonDataTypes PythonNumbers PythonCasting PythonStrings PythonStrings SlicingStrings ModifyStrings ConcatenateStrings FormatStrings EscapeCharacters StringMethods StringExercises PythonBooleans PythonOperators PythonLists PythonLists AccessListItems ChangeListItems AddListItems RemoveListItems LoopLists ListComprehension SortLists CopyLists JoinLists ListMethods ListExercises PythonTuples PythonTuples AccessTuples UpdateTuples UnpackTuples LoopTuples JoinTuples TupleMethods TupleExercises PythonSets PythonSets AccessSetItems AddSetItems RemoveSetItems LoopSets JoinSets SetMethods SetExercises PythonDictionaries PythonDictionaries AccessItems ChangeItems AddItems RemoveItems LoopDictionaries CopyDictionaries NestedDictionaries DictionaryMethods DictionaryExercise PythonIf...Else PythonWhileLoops PythonForLoops PythonFunctions PythonLambda PythonArrays PythonClasses/Objects PythonInheritance PythonIterators PythonScope PythonModules PythonDates PythonMath PythonJSON PythonRegEx PythonPIP PythonTry...Except PythonUserInput PythonStringFormatting FileHandling PythonFileHandling PythonReadFiles PythonWrite/CreateFiles PythonDeleteFiles PythonModules NumPyTutorial PandasTutorial SciPyTutorial DjangoTutorial PythonMatplotlib MatplotlibIntro MatplotlibGetStarted MatplotlibPyplot MatplotlibPlotting MatplotlibMarkers MatplotlibLine MatplotlibLabels MatplotlibGrid MatplotlibSubplot MatplotlibScatter MatplotlibBars MatplotlibHistograms MatplotlibPieCharts MachineLearning GettingStarted MeanMedianMode StandardDeviation Percentile DataDistribution NormalDataDistribution ScatterPlot LinearRegression PolynomialRegression MultipleRegression Scale Train/Test DecisionTree ConfusionMatrix HierarchicalClustering LogisticRegression GridSearch CategoricalData K-means BootstrapAggregation CrossValidation AUC-ROCCurve K-nearestneighbors PythonMySQL MySQLGetStarted MySQLCreateDatabase MySQLCreateTable MySQLInsert MySQLSelect MySQLWhere MySQLOrderBy MySQLDelete MySQLDropTable MySQLUpdate MySQLLimit MySQLJoin PythonMongoDB MongoDBGetStarted MongoDBCreateDatabase MongoDBCreateCollection MongoDBInsert MongoDBFind MongoDBQuery MongoDBSort MongoDBDelete MongoDBDropCollection MongoDBUpdate MongoDBLimit PythonReference PythonOverview PythonBuilt-inFunctions PythonStringMethods PythonListMethods PythonDictionaryMethods PythonTupleMethods PythonSetMethods PythonFileMethods PythonKeywords PythonExceptions PythonGlossary ModuleReference RandomModule RequestsModule StatisticsModule MathModule cMathModule PythonHowTo RemoveListDuplicates ReverseaString AddTwoNumbers PythonExamples PythonExamples PythonCompiler PythonExercises PythonQuiz PythonCertificate PythonRegEx ❮Previous Next❯ ARegEx,orRegularExpression,isasequenceofcharactersthatformsasearchpattern. RegExcanbeusedtocheckifastringcontainsthespecifiedsearchpattern. RegExModule Pythonhasabuilt-inpackagecalledre,whichcanbeusedtoworkwith RegularExpressions. Importtheremodule: importre RegExinPython Whenyouhaveimportedtheremodule,you canstartusingregularexpressions: Example Searchthestringtoseeifitstartswith"The"andendswith"Spain": import retxt="TheraininSpain"x=re.search("^The.*Spain$",txt) TryitYourself» RegExFunctions Theremoduleoffersasetoffunctionsthatallows ustosearchastringforamatch: Function Description findall Returnsalistcontainingallmatches search ReturnsaMatchobjectifthereisamatchanywhereinthestring split Returnsalistwherethestringhasbeensplitateachmatch sub Replacesoneormanymatcheswithastring Metacharacters Metacharactersarecharacterswithaspecialmeaning: Character Description Example Tryit [] Asetofcharacters "[a-m]" Tryit» \ Signalsaspecialsequence(canalsobeusedtoescapespecialcharacters) "\d" Tryit» . Anycharacter(exceptnewlinecharacter) "he..o" Tryit» ^ Startswith "^hello" Tryit» $ Endswith "planet$" Tryit» * Zeroormoreoccurrences "he.*o" Tryit» + Oneormoreoccurrences "he.+o" Tryit» ? Zerooroneoccurrences "he.?o" Tryit» {} Exactlythespecifiednumberofoccurrences "he.{2}o" Tryit» | Eitheror "falls|stays" Tryit» () Captureandgroup     SpecialSequences Aspecialsequenceisa\followedbyoneofthecharactersinthelistbelow,andhasaspecialmeaning: Character Description Example Tryit \A Returnsamatchifthespecifiedcharactersareatthebeginningofthe string "\AThe" Tryit» \b Returnsamatchwherethespecifiedcharactersareatthebeginningoratthe endofaword(the"r"inthebeginningismakingsurethatthestringis beingtreatedasa"rawstring") r"\bain"r"ain\b" Tryit» Tryit» \B Returnsamatchwherethespecifiedcharactersarepresent,butNOTatthebeginning (orat theend)ofaword(the"r"inthebeginningismakingsurethatthestring isbeingtreatedasa"rawstring") r"\Bain"r"ain\B" Tryit» Tryit» \d Returnsamatchwherethestringcontainsdigits(numbersfrom0-9) "\d" Tryit» \D ReturnsamatchwherethestringDOESNOTcontaindigits "\D" Tryit» \s Returnsamatchwherethestringcontainsawhitespacecharacter "\s" Tryit» \S ReturnsamatchwherethestringDOESNOTcontainawhitespacecharacter "\S" Tryit» \w Returnsamatchwherethestringcontainsanywordcharacters(charactersfrom atoZ,digitsfrom0-9,andtheunderscore_character) "\w" Tryit» \W ReturnsamatchwherethestringDOESNOTcontainanywordcharacters "\W" Tryit» \Z Returnsamatchifthespecifiedcharactersareattheendofthestring "Spain\Z" Tryit» Sets Asetisasetofcharactersinsideapairofsquarebrackets []withaspecialmeaning: Set Description Tryit [arn] Returnsamatchwhereoneofthespecifiedcharacters(a, r,orn)is present Tryit» [a-n] Returnsamatchforanylowercasecharacter,alphabeticallybetween aandn Tryit» [^arn] ReturnsamatchforanycharacterEXCEPTa, r,andn Tryit» [0123] Returnsamatchwhereanyofthespecifieddigits(0, 1,2,or 3)are present Tryit» [0-9] Returnsamatchforanydigitbetween 0and9 Tryit» [0-5][0-9] Returnsamatchforanytwo-digitnumbersfrom00and 59 Tryit» [a-zA-Z] Returnsamatchforanycharacteralphabeticallybetween aandz,lowercaseORuppercase Tryit» [+] Insets,+,*, .,|, (),$,{} hasnospecialmeaning,so[+]means:returnamatchforany +characterinthestring Tryit»   Thefindall()Function Thefindall()functionreturnsalistcontainingallmatches. Example Printalistofallmatches: importretxt="TheraininSpain"x=re.findall("ai", txt) print(x) TryitYourself» Thelistcontainsthematchesintheordertheyarefound. Ifnomatchesarefound,anemptylistisreturned: Example Returnanemptylistifnomatchwasfound: importretxt="TheraininSpain"x=re.findall("Portugal", txt) print(x) TryitYourself»   Thesearch()Function Thesearch()functionsearchesthestring foramatch,andreturnsaMatchobjectifthereisa match. Ifthereismorethanonematch, onlythefirstoccurrenceofthematchwillbereturned: Example Searchforthefirstwhite-spacecharacterinthestring: importretxt="TheraininSpain"x=re.search("\s", txt) print("Thefirstwhite-spacecharacterislocatedin position:",x.start()) TryitYourself» Ifnomatchesarefound,thevalueNoneisreturned: Example Makeasearchthatreturnsnomatch: importretxt="TheraininSpain"x=re.search("Portugal", txt) print(x) TryitYourself»   Thesplit()Function Thesplit()functionreturnsalistwhere thestringhasbeensplitateachmatch: Example Splitateachwhite-spacecharacter: importretxt="TheraininSpain"x=re.split("\s", txt) print(x) TryitYourself» Youcancontrolthenumberofoccurrencesbyspecifyingthe maxsplit parameter: Example Splitthestringonlyatthefirstoccurrence: importretxt="TheraininSpain"x=re.split("\s", txt, 1) print(x) TryitYourself»   Thesub()Function Thesub()functionreplacesthematcheswith thetextofyourchoice: Example Replaceeverywhite-spacecharacterwiththenumber9: importretxt="TheraininSpain"x=re.sub("\s", "9",txt) print(x) TryitYourself» Youcancontrolthenumberofreplacementsbyspecifyingthe count parameter: Example Replacethefirst2occurrences: importretxt="TheraininSpain"x=re.sub("\s", "9",txt,2) print(x) TryitYourself»   MatchObject AMatchObjectisanobjectcontaininginformation aboutthesearchandtheresult. Note:Ifthereisnomatch,thevalueNonewillbe returned,insteadoftheMatchObject. Example DoasearchthatwillreturnaMatchObject: importretxt="TheraininSpain"x=re.search("ai", txt) print(x)#thiswillprintanobject TryitYourself» TheMatchobjecthaspropertiesandmethodsusedtoretrieveinformation aboutthesearch,andtheresult: .span()returnsatuplecontainingthestart-,andendpositionsofthematch. .stringreturnsthestringpassedintothefunction .group()returnsthepartofthestringwheretherewasamatch Example Printtheposition(start-andend-position)ofthefirstmatchoccurrence. Theregularexpressionlooksforanywordsthatstartswithanuppercase "S": importre txt="TheraininSpain" x=re.search(r"\bS\w+",txt) print(x.span()) TryitYourself» Example Printthestringpassedintothefunction: importre txt="TheraininSpain" x=re.search(r"\bS\w+",txt) print(x.string) TryitYourself» Example Printthepartofthestringwheretherewasamatch. Theregularexpressionlooksforanywordsthatstartswithanuppercase "S": importre txt="TheraininSpain" x=re.search(r"\bS\w+",txt) print(x.group()) TryitYourself» Note:Ifthereisnomatch,thevalueNonewillbe returned,insteadoftheMatchObject. ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame



請為這篇文章評分?