Regular Expressions - JavaScript | MDN - LIA
文章推薦指數: 80 %
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects.
Skiptomaincontent
Selectlanguage
Skiptosearch
Languages
বাংলা(বাংলাদেশ)
Deutsch
Español
Français
日本語
Português(do Brasil)
Русский
ไทย
TiếngViệt
中文(简体)
正體中文(繁體)
Addatranslation
EditAdvanced
Advanced
History
Printthispage
MDN
Webtechnologyfordevelopers
JavaScript
JavaScriptGuide
RegularExpressions
YourSearchResults
RegularExpressions
ShowSidebar
InThisArticle
CreatingaregularexpressionWritingaregularexpressionpatternUsingsimplepatternsUsingspecialcharactersUsingparenthesesWorkingwithregularexpressionsUsingparenthesizedsubstringmatchesAdvancedsearchingwithflagsExamplesChangingtheorderinaninputstringUsingspecialcharacterstoverifyinput
«PreviousNext»
Regularexpressionsarepatternsusedtomatchcharactercombinationsinstrings.InJavaScript,regularexpressionsarealsoobjects.Thesepatternsareusedwiththeexecand testmethodsofRegExp,andwiththe match,replace, search,and splitmethodsof String.ThischapterdescribesJavaScriptregularexpressions.
Creatingaregularexpression
Youconstructaregularexpressioninoneoftwoways:
Usingaregularexpressionliteral,asfollows:
varre=/ab+c/;
Regularexpressionliteralsprovidecompilationoftheregularexpressionwhenthescriptisloaded.Whentheregularexpressionwillremainconstant,usethisforbetterperformance.
OrcallingtheconstructorfunctionoftheRegExpobject,asfollows:
varre=newRegExp("ab+c");
Usingtheconstructorfunctionprovidesruntimecompilationoftheregularexpression.Usetheconstructorfunctionwhenyouknowtheregularexpressionpatternwillbechanging,oryoudon'tknowthepatternandaregettingitfromanothersource,suchasuserinput.
Writingaregularexpressionpattern
Aregularexpressionpatterniscomposedofsimplecharacters,suchas/abc/,oracombinationofsimpleandspecialcharacters,suchas/ab*c/or/Chapter(\d+)\.\d*/.Thelastexampleincludesparentheseswhichareusedasamemorydevice.Thematchmadewiththispartofthepatternisrememberedforlateruse,asdescribedinUsingparenthesizedsubstringmatches.
Usingsimplepatterns
Simplepatternsareconstructedofcharactersforwhichyouwanttofindadirectmatch.Forexample,thepattern/abc/matchescharactercombinationsinstringsonlywhenexactlythecharacters'abc'occurtogetherandinthatorder.Suchamatchwouldsucceedinthestrings"Hi,doyouknowyourabc's?"and"Thelatestairplanedesignsevolvedfromslabcraft."Inbothcasesthematchiswiththesubstring'abc'.Thereisnomatchinthestring'Grabcrab'becausewhileitcontainsthesubstring'abc',itdoesnotcontaintheexactsubstring'abc'.
Usingspecialcharacters
Whenthesearchforamatchrequiressomethingmorethanadirectmatch,suchasfindingoneormoreb's,orfindingwhitespace,thepatternincludesspecialcharacters.Forexample,thepattern/ab*c/matchesanycharactercombinationinwhichasingle'a'isfollowedbyzeroormore'b's(*means0ormoreoccurrencesoftheprecedingitem)andthenimmediatelyfollowedby'c'.Inthestring"cbbabbbbcdebc,"thepatternmatchesthesubstring'abbbbc'.
Thefollowingtableprovidesacompletelistanddescriptionofthespecialcharactersthatcanbeusedinregularexpressions.
Specialcharactersinregularexpressions.
Character
Meaning
\
Matchesaccordingtothefollowingrules:
Abackslashthatprecedesanon-specialcharacterindicatesthatthenextcharacterisspecialandisnottobeinterpretedliterally.Forexample,a'b'withoutapreceding'\'generallymatcheslowercase'b'swherevertheyoccur.Buta'\b'byitselfdoesn'tmatchanycharacter;itformsthespecialwordboundarycharacter.
Abackslashthatprecedesaspecialcharacterindicatesthatthenextcharacterisnotspecialandshouldbeinterpretedliterally.Forexample,thepattern/a*/reliesonthespecialcharacter'*'tomatch0ormorea's.Bycontrast,thepattern/a\*/removesthespecialnessofthe'*'toenablematcheswithstringslike'a*'.
Donotforgettoescape\itselfwhileusingtheRegExp("pattern")notationbecause\isalsoanescapecharacterinstrings.
^
Matchesbeginningofinput.Ifthemultilineflagissettotrue,alsomatchesimmediatelyafteralinebreakcharacter.
Forexample,/^A/doesnotmatchthe'A'in"anA",butdoesmatchthe'A'in"AnE".
The'^'hasadifferentmeaningwhenitappearsasthefirstcharacterinacharactersetpattern.Seecomplementedcharactersetsfordetailsandanexample.
$
Matchesendofinput.Ifthemultilineflagissettotrue,alsomatchesimmediatelybeforealinebreakcharacter.
Forexample,/t$/doesnotmatchthe't'in"eater",butdoesmatchitin"eat".
*
Matchestheprecedingcharacter0ormoretimes.Equivalentto{0,}.
Forexample,/bo*/matches'boooo'in"Aghostbooooed"and'b'in"Abirdwarbled",butnothingin"Agoatgrunted".
+
Matchestheprecedingcharacter1ormoretimes.Equivalentto{1,}.
Forexample,/a+/matchesthe'a'in"candy"andallthea'sin"caaaaaaandy",butnothingin"cndy".
?
Matchestheprecedingcharacter0or1time.Equivalentto{0,1}.
Forexample,/e?le?/matchesthe'el'in"angel"andthe'le'in"angle"andalsothe'l'in"oslo".
Ifusedimmediatelyafteranyofthequantifiers*,+,?,or{},makesthequantifiernon-greedy(matchingthefewestpossiblecharacters),asopposedtothedefault,whichisgreedy(matchingasmanycharactersaspossible).Forexample,applying/\d+/to"123abc"matches"123".Butapplying/\d+?/tothatsamestringmatchesonlythe"1".
Alsousedinlookaheadassertions,asdescribedinthex(?=y)andx(?!y)entriesofthistable.
.
(Thedecimalpoint)matchesanysinglecharacterexceptthenewlinecharacter.
Forexample,/.n/matches'an'and'on'in"nay,anappleisonthetree",butnot'nay'.
(x)
Matches'x'andremembersthematch,asthefollowingexampleshows.Theparenthesesarecalledcapturingparentheses.
The'(foo)'and'(bar)'inthepattern/(foo)(bar)\1\2/matchandrememberthefirsttwowordsinthestring"foobarfoobar".The\1and\2inthepatternmatchthestring'slasttwowords.Notethat\1,\2,\nareusedinthematchingpartoftheregex.Inthereplacementpartofaregexthesyntax$1,$2,$nmustbeused,e.g.:'barfoo'.replace(/(...)(...)/,'$2$1').
(?:x)
Matches'x'butdoesnotrememberthematch.Theparenthesesarecallednon-capturingparentheses,andletyoudefinesubexpressionsforregularexpressionoperatorstoworkwith.Considerthesampleexpression/(?:foo){1,2}/.Iftheexpressionwas/foo{1,2}/,the{1,2}characterswouldapplyonlytothelast'o'in'foo'.Withthenon-capturingparentheses,the{1,2}appliestotheentireword'foo'.
x(?=y)
Matches'x'onlyif'x'isfollowedby'y'.Thisiscalledalookahead.
Forexample,/Jack(?=Sprat)/matches'Jack'onlyifitisfollowedby'Sprat'./Jack(?=Sprat|Frost)/matches'Jack'onlyifitisfollowedby'Sprat'or'Frost'.However,neither'Sprat'nor'Frost'ispartofthematchresults.
x(?!y)
Matches'x'onlyif'x'isnotfollowedby'y'.Thisiscalledanegatedlookahead.
Forexample,/\d+(?!\.)/matchesanumberonlyifitisnotfollowedbyadecimalpoint.Theregularexpression/\d+(?!\.)/.exec("3.141")matches'141'butnot'3.141'.
x|y
Matcheseither'x'or'y'.
Forexample,/green|red/matches'green'in"greenapple"and'red'in"redapple."
{n}
Matchesexactlynoccurrencesoftheprecedingcharacter.Nmustbeapositiveinteger.
Forexample,/a{2}/doesn'tmatchthe'a'in"candy,"butitdoesmatchallofthea'sin"caandy,"andthefirsttwoa'sin"caaandy."
{n,m}
Wherenandmarepositiveintegersandn<=m.Matchesatleastnandatmostmoccurrencesoftheprecedingcharacter.Whenmisomitted,it'streatedas∞.
Forexample,/a{1,3}/matchesnothingin"cndy",the'a'in"candy,"thefirsttwoa'sin"caandy,"andthefirstthreea'sin"caaaaaaandy".Noticethatwhenmatching"caaaaaaandy",thematchis"aaa",eventhoughtheoriginalstringhadmorea'sinit.
[xyz]
Characterset.Thispatterntypematchesanyoneofthecharactersinthebrackets,includingescapesequences.Specialcharacterslikethedot(.)andasterisk(*)arenotspecialinsideacharacterset,sotheydon'tneedtobeescaped.Youcanspecifyarangeofcharactersbyusingahyphen,asthefollowingexamplesillustrate.
Thepattern[a-d],whichperformsthesamematchas[abcd],matchesthe'b'in"brisket"andthe'c'in"city".Thepatterns/[a-z.]+/and/[\w.]+/matchtheentirestring"test.i.ng".
[^xyz]
Anegatedorcomplementedcharacterset.Thatis,itmatchesanythingthatisnotenclosedinthebrackets.Youcanspecifyarangeofcharactersbyusingahyphen.Everythingthatworksinthenormalcharactersetalsoworkshere.
Forexample,[^abc]isthesameas[^a-c].Theyinitiallymatch'r'in"brisket"and'h'in"chop."
[\b]
Matchesabackspace(U+0008).Youneedtousesquarebracketsifyouwanttomatchaliteralbackspacecharacter.(Nottobeconfusedwith\b.)
\b
Matchesawordboundary.Awordboundarymatchesthepositionwhereawordcharacterisnotfollowedorpreceededbyanotherword-character.Notethatamatchedwordboundaryisnotincludedinthematch.Inotherwords,thelengthofamatchedwordboundaryiszero.(Nottobeconfusedwith[\b].)
Examples:
/\bm/matchesthe'm'in"moon";
/oo\b/doesnotmatchthe'oo'in"moon",because'oo'isfollowedby'n'whichisawordcharacter;
/oon\b/matchesthe'oon'in"moon",because'oon'istheendofthestring,thusnotfollowedbyawordcharacter;
/\w\b\w/willnevermatchanything,becauseawordcharactercanneverbefollowedbybothanon-wordandawordcharacter.
Note: JavaScript'sregularexpressionenginedefinesaspecificsetofcharacterstobe"word"characters.Anycharacternotinthatsetisconsideredawordbreak.Thissetofcharactersisfairlylimited:itconsistssolelyofthe Romanalphabetinbothupper-andlower-case,decimaldigits,andtheunderscorecharacter.Accentedcharacters,suchas"é"or"ü"are,unfortunately,treatedaswordbreaks.
\B
Matchesanon-wordboundary.Thismatchesapositionwherethepreviousandnextcharacterareofthesametype:Eitherbothmustbewords,orbothmustbenon-words.Thebeginningandendofastringareconsiderednon-words.
Forexample,/\B../matches'oo'in"noonday",and/y\B./matches'ye'in"possiblyyesterday."
\cX
WhereXisacharacterrangingfromAtoZ.Matchesacontrolcharacterinastring.
Forexample,/\cM/matchescontrol-M(U+000D)inastring.
\d
Matchesadigitcharacter.Equivalentto[0-9].
Forexample,/\d/or/[0-9]/matches'2'in"B2isthesuitenumber."
\D
Matchesanynon-digitcharacter.Equivalentto[^0-9].
Forexample,/\D/or/[^0-9]/matches'B'in"B2isthesuitenumber."
\f
Matchesaformfeed(U+000C).
\n
Matchesalinefeed(U+000A).
\r
Matchesacarriagereturn(U+000D).
\s
Matchesasinglewhitespacecharacter,includingspace,tab,formfeed,linefeed.Equivalentto[\f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000].
Forexample,/\s\w*/matches'bar'in"foobar."
\S
Matchesasinglecharacterotherthanwhitespace.Equivalentto[^\f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000].
Forexample,/\S\w*/matches'foo'in"foobar."
\t
Matchesatab(U+0009).
\v
Matchesaverticaltab(U+000B).
\w
Matchesanyalphanumericcharacterincludingtheunderscore.Equivalentto[A-Za-z0-9_].
Forexample,/\w/matches'a'in"apple,"'5'in"$5.28,"and'3'in"3D."
\W
Matchesanynon-wordcharacter.Equivalentto[^A-Za-z0-9_].
Forexample,/\W/or/[^A-Za-z0-9_]/matches'%'in"50%."
\n
Wherenisapositiveinteger,abackreferencetothelastsubstringmatchingthenparentheticalintheregularexpression(countingleftparentheses).
Forexample,/apple(,)\sorange\1/matches'apple,orange,'in"apple,orange,cherry,peach."
\0
MatchesaNULL(U+0000)character.Donotfollowthiswithanotherdigit,because\0 Enteryourphonenumber(withareacode)andthenclick"Check".
Theexpectedformatislike###-###-####.
延伸文章資訊
- 1regex mdn Code Example - Javascript - Code Grepper
using regex in javascript ... Tests website Regular Expression against document.location (current...
- 2學JS的心路歷程Day12-正規表達式Regular Expression
What does regex' flag 'y' do? Javascript Regular Expressions , 表示法 · MDN-正規表達式 · [實用] 用Regular Ex...
- 3function* - JavaScript | MDN
- 4js regex match mdn - 掘金
js regex match mdn技术、学习、经验文章掘金开发者社区搜索结果。掘金是一个帮助开发者成长的社区,js regex match mdn技术文章由稀土上聚集的技术大牛和极客共同编辑 ...
- 5正規表示式- 術語表 - MDN Web Docs
正規表示式(Regular expressions,或是regex)是主宰著字符序列搜索的規則。