Quick-Start: Regex Cheat Sheet - RexEgg
文章推薦指數: 80 %
Regular Expressions Syntax Reference. Includes tables showing syntax, examples and matches. ⬅Menu:Allthepagesquicklinks⬇ FundamentalsBlackBeltProgramRegexinActionHumor&MoreAskRex Quick-Start:RegexCheatSheet Thetablesbelowareareferencetobasicregex.Whilereadingtherestofthesite,whenindoubt,youcanalwayscomebackandlookhere.(Ityouwantabookmark,here'sadirectlinktotheregexreferencetables).Iencourageyoutoprintthetablessoyouhaveacheatsheetonyourdeskforquickreference. Thetablesarenotexhaustive,fortworeasons.First,everyregexflavorisdifferent,andIdidn'twanttocrowdthepagewithoverlyexoticsyntax.Forafullreferencetotheparticularregexflavorsyou'llbeusing,it'salwaysbesttogostraighttothesource.Infact,forsomeregexengines(suchasPerl,PCRE,Javaand.NET)youmaywanttocheckonceayear,astheircreatorsoftenintroducenewfeatures. TheotherreasonthetablesarenotexhaustiveisthatIwantedthemtoserveasaquickintroductiontoregex.Ifyouareacompletebeginner,youshouldgetafirmgraspofbasicregexsyntaxjustbyreadingtheexamplesinthetables.ItriedtointroducefeaturesinalogicalorderandtokeepoutodditiesthatI'veneverseeninactualuse,suchasthe"bellcharacter".Withthesetablesasajumpingboard,youwillbeabletoadvancetomasterybyexploringtheotherpagesonthesite. Howtousethetables Thetablesaremeanttoserveasanacceleratedregexcourse,andtheyaremeanttobereadslowly,onelineatatime.Oneachline,intheleftmostcolumn,youwillfindanewelementofregexsyntax.Thenextcolumn,"Legend",explainswhattheelementmeans(orencodes)intheregexsyntax.Thenexttwocolumnsworkhandinhand:the"Example"columngivesavalidregularexpressionthatusestheelement,andthe"SampleMatch"columnpresentsatextstringthatcouldbematchedbytheregularexpression. Youcanreadthetablesonline,ofcourse,butifyousufferfromeventhemildestcaseofonline-ADD(attentiondeficitdisorder),likemostofus…Wellthen,Ihighlyrecommendyouprintthemout.You'llbeabletostudythemslowly,andtousethemasacheatsheetlater,whenyouarereadingtherestofthesiteorexperimentingwithyourownregularexpressions. Enjoy! Ifyouoverdose,makesurenottomissthenextpage,whichcomesbackdowntoEarthandtalksaboutsomereallycoolstuff:The1001waystouseRegex. RegexAcceleratedCourseandCheatSheet Foreasynavigation,herearesomejumpingpointstovarioussectionsofthepage: ✽Characters ✽Quantifiers ✽MoreCharacters ✽Logic ✽MoreWhite-Space ✽MoreQuantifiers ✽CharacterClasses ✽AnchorsandBoundaries ✽POSIXClasses ✽InlineModifiers ✽Lookarounds ✽CharacterClassOperations ✽OtherSyntax (directlink) Characters CharacterLegendExampleSampleMatch\dMostengines:onedigitfrom0to9file_\d\dfile_25\d.NET,Python3:oneUnicodedigitinanyscriptfile_\d\dfile_9੩\wMostengines:"wordcharacter":ASCIIletter,digitorunderscore\w-\w\w\wA-b_1\w.Python3:"wordcharacter":Unicodeletter,ideogram,digit,orunderscore\w-\w\w\w字-ま_۳\w.NET:"wordcharacter":Unicodeletter,ideogram,digit,orconnector\w-\w\w\w字-ま‿۳\sMostengines:"whitespacecharacter":space,tab,newline,carriagereturn,verticaltaba\sb\scabc\s.NET,Python3,JavaScript:"whitespacecharacter":anyUnicodeseparatora\sb\scabc\DOnecharacterthatisnotadigitasdefinedbyyourengine's\d\D\D\DABC\WOnecharacterthatisnotawordcharacterasdefinedbyyourengine's\w\W\W\W\W\W*-+=)\SOnecharacterthatisnotawhitespacecharacterasdefinedbyyourengine's\s\S\S\S\SYoyo (directlink) Quantifiers QuantifierLegendExampleSampleMatch+OneormoreVersion\w-\w+VersionA-b1_1{3}Exactlythreetimes\D{3}ABC{2,4}Twotofourtimes\d{2,4}156{3,}Threeormoretimes\w{3,}regex_tutorial*ZeroormoretimesA*B*C*AAACC?Onceornoneplurals?plural (directlink) MoreCharacters CharacterLegendExampleSampleMatch.Anycharacterexceptlinebreaka.cabc.Anycharacterexceptlinebreak.*whatever,man.\.Aperiod(specialcharacter:needstobeescapedbya\)a\.ca.c\Escapesaspecialcharacter\.\*\+\? \$\^\/\\.*+? $^/\\Escapesaspecialcharacter\[\{\(\)\}\][{()}] (directlink) Logic LogicLegendExampleSampleMatch|Alternation/ORoperand22|3333(…)CapturinggroupA(nt|pple)Apple(captures"pple")\1ContentsofGroup1r(\w)g\1xregex\2ContentsofGroup2(\d\d)\+(\d\d)=\2\+\112+65=65+12(?:…)Non-capturinggroupA(?:nt|pple)Apple (directlink) MoreWhite-Space CharacterLegendExampleSampleMatch\tTabT\t\w{2}T ab\rCarriagereturncharacterseebelow\nLinefeedcharacterseebelow\r\nLineseparatoronWindowsAB\r\nCDABCD\NPerl,PCRE(C,PHP,R…):onecharacterthatisnotalinebreak\N+ABC\hPerl,PCRE(C,PHP,R…),Java:onehorizontalwhitespacecharacter:taborUnicodespaceseparator\HOnecharacterthatisnotahorizontalwhitespace\v.NET,JavaScript,Python,Ruby:verticaltab\vPerl,PCRE(C,PHP,R…),Java:oneverticalwhitespacecharacter:linefeed,carriagereturn,verticaltab,formfeed,paragraphorlineseparator\VPerl,PCRE(C,PHP,R…),Java:anycharacterthatisnotaverticalwhitespace\RPerl,PCRE(C,PHP,R…),Java:onelinebreak(carriagereturn+linefeedpair,andallthecharactersmatchedby\v) (directlink) MoreQuantifiers QuantifierLegendExampleSampleMatch+The+(oneormore)is"greedy"\d+12345?Makesquantifiers"lazy"\d+?1in12345*The*(zeroormore)is"greedy"A*AAA?Makesquantifiers"lazy"A*?emptyinAAA{2,4}Twotofourtimes,"greedy"\w{2,4}abcd?Makesquantifiers"lazy"\w{2,4}?abinabcd (directlink) CharacterClasses CharacterLegendExampleSampleMatch[…]Oneofthecharactersinthebrackets[AEIOU]Oneuppercasevowel[…]OneofthecharactersinthebracketsT[ao]pTaporTop-Rangeindicator[a-z]Onelowercaseletter[x-y]Oneofthecharactersintherangefromxtoy[A-Z]+GREAT[…]Oneofthecharactersinthebrackets[AB1-5w-z]Oneofeither:A,B,1,2,3,4,5,w,x,y,z[x-y]Oneofthecharactersintherangefromxtoy[ -~]+CharactersintheprintablesectionoftheASCIItable.[^x]Onecharacterthatisnotx[^a-z]{3}A1![^x-y]Oneofthecharactersnotintherangefromxtoy[^ -~]+CharactersthatarenotintheprintablesectionoftheASCIItable.[\d\D]Onecharacterthatisadigitoranon-digit[\d\D]+Anycharacters,inc-ludingnewlines,whichtheregulardotdoesn'tmatch[\x41]Matchesthecharacterathexadecimalposition41intheASCIItable,i.e.A[\x41-\x45]{3}ABE (directlink) AnchorsandBoundaries AnchorLegendExampleSampleMatch^Startofstringorstartoflinedependingonmultilinemode.(Butwhen[^insidebrackets],itmeans"not")^abc.*abc(linestart)$Endofstringorendoflinedependingonmultilinemode.Manyengine-dependentsubtleties..*?theend$thisistheend\ABeginningofstring(allmajorenginesexceptJS)\Aabc[\d\D]*abc(string......start)\zVeryendofthestringNotavailableinPythonandJStheend\zthisis...\n...theend\ZEndofstringor(exceptPython)beforefinallinebreakNotavailableinJStheend\Zthisis...\n...theend\n\GBeginningofStringorEndofPreviousMatch .NET,Java,PCRE(C,PHP,R…),Perl,Ruby\bWordboundaryMostengines:positionwhereonesideonlyisanASCIIletter,digitorunderscoreBob.*\bcat\bBobatethecat\bWordboundary.NET,Java,Python3,Ruby:positionwhereonesideonlyisaUnicodeletter,digitorunderscoreBob.*\b\кошка\bBobatetheкошка\BNotawordboundaryc.*\Bcat\B.*copycats (directlink) POSIXClasses CharacterLegendExampleSampleMatch[:alpha:]PCRE(C,PHP,R…):ASCIIlettersA-Zanda-z[8[:alpha:]]+WellDone88[:alpha:]Ruby2:Unicodeletterorideogram[[:alpha:]\d]+кошка99[:alnum:]PCRE(C,PHP,R…):ASCIIdigitsandlettersA-Zanda-z[[:alnum:]]{10}ABCDE12345[:alnum:]Ruby2:Unicodedigit,letterorideogram[[:alnum:]]{10}кошка90210[:punct:]PCRE(C,PHP,R…):ASCIIpunctuationmark[[:punct:]]+?!.,:;[:punct:]Ruby:Unicodepunctuationmark[[:punct:]]+‽,:〽⁆ (directlink) InlineModifiers NoneofthesearesupportedinJavaScript.InRuby,bewareof(?s)and(?m). ModifierLegendExampleSampleMatch(?i)Case-insensitivemode (exceptJavaScript)(?i)MondaymonDAY(?s)DOTALLmode(exceptJSandRuby).Thedot(.)matchesnewlinecharacters(\r\n).Alsoknownas"single-linemode"becausethedottreatstheentireinputasasingleline(?s)FromA.*toZFromAtoZ(?m)Multilinemode (exceptRubyandJS)^and$matchatthebeginningandendofeveryline(?m)1\r\n^2$\r\n^3$123(?m)InRuby:thesameas(?s)inotherengines,i.e.DOTALLmode,i.e.dotmatcheslinebreaks(?m)FromA.*toZFromAtoZ(?x)Free-SpacingModemode (exceptJavaScript).Alsoknownascommentmodeorwhitespacemode(?x)#thisisa#commentabc#writeonmultiple#lines[]d#spacesmustbe#inbracketsabcd(?n).NET,PCRE10.30+:namedcaptureonlyTurnsall(parentheses)intonon-capturegroups.Tocapture,usenamedgroups.(?d)Java:UnixlinebreaksonlyThedotandthe^and$anchorsareonlyaffectedby\n(?^)PCRE10.32+:unsetmodifiersUnsetsismnxmodifiers (directlink) Lookarounds LookaroundLegendExampleSampleMatch(?=…)Positivelookahead(?=\d{10})\d{5}01234in0123456789(?<=…)Positivelookbehind(?<=\d)catcatin1cat(?!…)Negativelookahead(?!theatre)the\w+theme(?
延伸文章資訊
- 1Quick-Start: Regex Cheat Sheet - RexEgg
Regular Expressions Syntax Reference. Includes tables showing syntax, examples and matches.
- 2Regular Expressions Cheat Sheet by DaveChild
A quick reference guide for regular expressions (regex), including symbols, ranges, grouping, ass...
- 3RegExLib.com Regular Expression Cheat Sheet (.NET)
RegExLib.com Regular Expression Cheat Sheet (.NET). Metacharacters Defined. MChar, Definition. ^,...
- 4Regular Expressions cheat sheet
Regular Expressions cheat sheet. Basic matching. Each symbol matches a single character: anything...
- 5RegEX Cheat Sheet & Quick Reference
This is a quick cheat sheet to getting started with regular expressions. ... re.compile, Compile ...