Regular Expression Syntax Reference

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

Example1: When pattern "\d\d" matches "abc123", match result: success; substring matched: "12"; position: starts at 3, ends at 5. ... Example2: When pattern "a.\d ... Home Start Engine Tools Applications Content: ·Introduction ------------ ·Common ·Escapedcharacter ·Charactersets ·Customsets ·Quantifier ·Specialpuncts ------------ ·Greedyorreluctant ·Backward ·Assertion ------------ ·Othercommon ·Moreprompts   RegexTool: RegexMatchTracer 2.1-Free RegexMatchTracer3.0-Newrelease (Thenewreleasewilltellyouwhereinyour regexfailedtomatch!) RegularExpressionSyntax [Allrightsreserved:http://www.regexlab.com/en/regref.htm] Introduction    Regularexpressionistoexpressacharacteristicinastring,andthentomatchanotherstringwiththecharacteristic.Forexample,pattern"ab+"means"one'a'andatleastone'b'",so"ab","abb","abbbbbbb"matchthepattern.    Regularexpressionisusedto:(1)testastringwhetheritmatchesapattern,suchasaemailaddress.(2)tofindasubstringwhichmatchescertainpattern,fromawholetext.(3)todocomplexreplacementinatext.    Itisverysimpletostudyregularexpressionsyntax,andthefewabstractconceptscanbeunderstoodeasilytoo.Manyarticlesdoesnotintroduceitsconceptsfromsimpleonestoabstractonesstepbystep,sosomepersonsmayfeelitisdifficult tostudy.Ontheotherhand,eachregularexpressionengine'sdocumentwilldescribeitsspecialfunction,butthispartofspecialfunctionisnotwhatweshouldstudyfirst.    Everyexampleinthisarticlehasalinktotestpage.Nowlet'sbegin! 1.RegularExpressionBasicSyntax 1.1CommonCharacters    Letters,numbers,theunderline,andpunctuationswithnospecialdefinitionare"commoncharacters".Whenregularexpressionmatchesastring,acommoncharactercanmatchthesamecharacter.    Example1:Whenpattern"c"matchesstring"abcde",matchresult:success;substringmatched:"c";position:startsat2,endsat3.    Example2:Whenpattern"bcd"matchesstring"abcde",matchresult:success;substringmatched:"bcd";position:startsat1,endsat4. 1.2Simpleescapedcharacters    Nonprintingcharacterswhichweknow: Expression Matches \r,\n Carriagereturn,newlinecharacter \t Tabs \\ Matches"\"itself    Somepunctuationsarespeciallydefinedinregularexpression.Tomatchthesecharactersinstring,add"\"inpattern.Forexample:^,$hasspecialdefinition,soweneedtouse"\^"and"\$"tomatchthem. Expression Matches \^ Matches"^"itself \$ Matches"$"itself \. Matchesdot(.)itself    Theseescapedcharactershavethesameeffectas"commoncharacters":tomatchacertaincharacter.    Example1:Whenpattern"\$d"matchesstring"abc$de",matchresult:success;substringmatched:"$d";position:startsat3,endsat5. 1.3Expressionmatchesanyoneofmanycharacters    Someexpressionscanmatchanyoneofmanycharacters.Forexample:"\d"canmatchanynumbercharacter.Eachoftheseexpressionscanmatchonlyonecharacteratonetime,thoughtheycanmatchanycharacterofacertaingroupofcharacters. Expression Matches \d Anydigitcharacter,anyoneof0~9 \w Anyalpha,numeric,underline,anyoneofA~Z,a~z,0~9,_ \s Anyoneofspace,tab,newline,return,ornewpagecharacter . '.'matchesanycharacterexceptthenewlinecharacter(\n)    Example1:Whenpattern"\d\d"matches"abc123",matchresult:success;substringmatched:"12";position:startsat3,endsat5.    Example2:Whenpattern"a.\d"matches"aaa100",matchresult:success;substringmatched:"aa1";position:startsat1,endsat4. 1.4Customexpressionmatchesanyoneofmanycharacters    Expressionusessquarebrackets[]tocontainaseriesofcharacters,itcanmatchanyoneofthem.Uses[^]tocontainaseriesofcharacters,itcanmatchanyonecharacterexceptcharacterscontained. Expression Matches [ab5@] Matches"a"or"b"or"5"or"@" [^abc] Matchesanycharacterexcept"a","b","c" [f-k] Anycharacteramong"f"~"k" [^A-F0-3] Anycharacterexcept"A"~"F","0"~"3"    Example1:Whenpattern"[bcd][bcd]"matches"abc123" ,matchresult:success;substringmatched:"bc";position:startsat1,endsat3.     Example2:Whenpattern"[^abc]"matches"abc123",matchresult:success;substringmatched:"1";position:startsat3,endsat4. 1.5Specialexpressiontoquantifymatching    Allexpressionsintroducedbeforecanmatchcharacteronlyonetime.Ifaexpressionisfollowedbyaquantifier,itcanmatchesmorethanonetimes.    Forexample:wecanusethepattern"[bcd]{2}"insteadof"[bcd][bcd]". Expression Function {n} Matchexactlyntimes,example:"\w{2}"equals"\w\w";"a{5}"equals "aaaaa" {m,n} Atleastmbutnomorethanntimes: "ba{1,3}"matches"ba","baa","baaa" {m,} Matchatleastntimes: "\w\d{2,}"matches"a12","_456","M12344"... ? Match1or0times,equivalentto{0,1}: "a[cd]?"matches"a","ac","ad". + Match1ormoretimes,equivalentto{1,}: "a+b"matches"ab","aab","aaab"... * Match0ormoretimes,equivalentto{0,}: "\^*b"matches"b","^^^b"...     Example1:Whenpattern"\d+\.?\d*"matches"Itcosts$12.5",matchresult:success;substringmatched:"12.5";position:startsat10,endsat14.     Example2:Whenpattern"go{2,8}gle"matches"Adsbygoooooogle",matchresult:success;substringmatched:"goooooogle";position:startsat7,endsat17. 1.6Somespecialpunctuationswithabstractfunction    Somepunctuationsinpatternhavespecialfunction: Expression Function ^ Matchthebeginningofthestring $ Matchtheendofthestring \b Matchawordboundary    Moreexamplestohelpyoutounderstand.    Example1:Whenpattern"^aaa"matches"xxxaaaxxx",matchresult:failed.Because"^"mustmatchthebeginningofthestring.Itcouldmatchsuccessfullyonconditionthat"aaa"isatthe beginningofthestring,suchas"aaaxxxxxx".    Example2:Whenpattern"aaa$"matches"xxxaaaxxx",matchresult:failed.Bacause"$"mustmatchtheendofthestring.Itcouldmatchsuccessfullyonconditionthat"aaa"isattheendofthe string,suchas"xxxxxxaaa".    Example3:Whenpattern".\b."matches"@@@abc",matchresult:success;substringmatched:"@a";position:startsat2,endsat4.    Furtherexplanation:"\b"issimilarto"^"and"$",matchesnocharacteritself,butitrequirea'\w'characteratitsoneside,anothernot'\w'characterattheotherside.    Example4:Whenpattern"\bend\b"matches"weekend,endfor,end",matchresult:success;substringmatched:"end";position:startsat15,endsat18.    Somespecialpunctuationcanmakeeffectonothersub-patterns: Expression Function | Alternation,matcheseitherleftsideorrightside () (1).Letsub-patternsinittobeawholepartwhenitisquantified. (2).Matchresultofsub-patternsinitcanberetrievedindividually    Example5:Whenpattern"Tom|Jack"matchesstring"I'mTom,heisJack",matchresult:success;substringmatched:"Tom";position:startsat4,endsat7.Whenmatchnext, matchresult:success;substringmatched:"Jack";position:startsat15,endsat19.    Example6:Whenpattern"(go\s*)+"matches"Let'sgogogo!",matchresult:success;substringmatched:"gogogo";position:startsat6,endsat14.    Example7:Whenpattern"¥(\d+\.?\d*)"matches"$10.9,¥20.5",matchresult:success;substringmatched:"¥20.5";position:startsat6,endsat10.Match resultofsub-patternsin"()"is:"20.5". 2.Regularexpressionadvancedsyntax 2.1Reluctantorgreedyquantifiers    Thereareservalmethodtoquantifysubpattern,suchas:"{m,n}","{m,}","?","*","+".Bydefault,aquantifiedsubpatternis"greedy",thatis,itwillmatchasmanytimesaspossible(givenaparticularstartinglocation)whilestillallowing therestofthepatterntomatch.Forexample,tomatch"dxxxdxxxd": Expression Matchresult (d)(\w+) "\w+"matchesallcharacters"xxxdxxxd"behindof"d" (d)(\w+)(d) "\w+"matchesallcharacters"xxxdxxx"betweenthefirst"d"andthelast"d".Inordertoletthewholepatternmatchsuccess,"\w"hastogiveupthelast"d",althoughitcanmatchthelast"d"too.    Thusitcanbeseenthat:when"\w+"matches,itwillmatchasmanycharactersaspossible.Inthesecondexample,itdoesnotmatchthelast"d",butthisisinordertoletthewholepatternmatchsuccessfully.Patternwith"*"or"{m,n}"will alsomatchasmanytimesaspossible,patternwith"?"willmatchifpossible.Thistypeofmatchingiscalled"greedymatching".。

   ReluctantMatching:    Tofollowthequantifierwitha"?",itcanletthepatterntomatchtheminimumnumberoftimespossible.Thistypeofmatchingiscalledreluctantmatching.Inordertoletthewholepatternmatchsuccessfully,thereluctantpatternmaymatcha fewmoretimesifitisrequired.Forexample,tomatch"dxxxdxxxd": Expression Matchresult (d)(\w+?) "\w+?"matchasfewtimesaspossible,so"\w+?"matchesonlyone"x" (d)(\w+?)(d) Inordertoletthewholepatternmatchsuccessfully,"\w+?"hastomatch"xxx".So,matchresultis:"\w+?"matches"xxx"    Moreexamples:    Example1:Whenpattern"

(.*)"matches"

aa

bb

",matchresult: success;substringmatched:thewhole"

aa

bb

",""inthepatternmatchesthelast""inthestring.    Example2:Forcomparison,whenpattern"(.*?)"matchesthestringinexample1,itmatches "

aa

".Whenmatchnext,thenext"

bb

"canbematched. 2.2Referringtomatchedsubstring\1,\2...    Duringtheprocessofmatching,thematchresultsofsubpatternbetweenparentheses"()"arerecordedforlateruse.Whenretrievingmatchresults,thosematchresultofsubpatterncanberetrievedindividually,andthishasbeendemonstrated manytimesinformerexamples.Inpractice,parentheses"()"mustbeusedtogetwhatwewantindeedaftermatch,suchas"(.*?)".    Infact,thosematchresultofsubpatternbetweenparenthesescanbeusednotonlyaftermatching,butalsoduringmatching.Thelatterpartofsubpattern,canreferthematchresultofformersubpattern.Usage:"\"plusanumbertorefertothe correspondingsubstring."\1"refersto1stpairofparentheses'matchresult,"\2"refersto2ndpairofparentheses'matchresult.    Examples:     Example1:Whenpattern"('|")(.*?)(\1)"matches"'Hello',"World"",matchresult:success;substringmatched:"'Hello'";whenmatchnext,substringmatched:""World"".    Example2:Whenpattern"(\w)\1{4,}"matches"aabbbbabcdefgccccc111121111999999999",matchresult:success;substringmatched: "ccccc";whenmatchnext,substringmatched"999999999".Thispatternrequireacharacterof"\w"torepeatatleast5times. Payattentiontocomparisonwith"\w{5,}".     Example3:Whenpattern".*?\1>"matches"",matchresult:success.Ifboth""and""arenot"td",thematchwillfail. 2.3Lookaheadassertion;Lookbehindassertion    Informerchapters,Ihaveintroducedservalpunctuationswithspecialfunction:"^","$","\b".Theyalldonotmatchanycharacters,buttheyallrequirecertainconditionsontheirposition.Now,thischapterwillintroducemoremethodstoadd conditionsonthegapbetweencharacters.    Lookaheadassertion:"(?=xxxxx)","(?!xxxxx)"    Format:"(?=xxxxx)",theconditionwhichitaddonthegapisthat:stringontherightsideofthegapmustbeabetomatchthesubpattern"xxxxx"betweentheparentheses.Itisjustacondition,notamatchoperation,sothereisnomatchresult.    Example1:Whenpattern"Windows(?=NT|XP)"matches"Windows98,WindowsNT,Windows2000",itcanmatchonly"Windows"of"WindowsNT",the other"Windows"couldnotbematched.    Example2:Whenpattern"(\w)((?=\1\1\1)(\1))+"matches"aaaffffff999999999",itcanmatchfirst4"f"samongthe6"f"s,itcanmatch first7"9"samong9"9"s.    Format:"(?!xxxxx)",stringontherightsideofthegapmustnotbeabletomatchthesubpattern"xxxxx".     Example3:Whenpattern"((?!\bstop\b).)+"matches"fdjkaljfdlstopfjdslafdj",itwillmatchfromthebeginningofstringtothepositionof"stop".Ifthereisno"stop"inthestring,thepatternwillmatchthewholestring.    Example4:Whenpattern"do(?!\w)"matches"done,do,dog",itcanonlymatch"do".Here,"(?!\w)"hasthesameeffectas"\b".    Lookbehindassertion:"(?<=xxxxx)","(?


請為這篇文章評分?