Regular expression syntax cheatsheet - JavaScript | MDN
文章推薦指數: 80 %
This page provides an overall cheat sheet of all the capabilities of RegExp syntax by aggregating the content of the articles in the RegExp ...
SkiptomaincontentSkiptosearchSkiptoselectlanguageReferencesJavaScriptJavaScriptGuideRegularexpressionsRegularexpressionsyntaxcheatsheetArticleActionsEnglish(US)CharacterclassesAssertionsGroupsandbackreferencesQuantifiersUnicodepropertyescapesRelatedTopics
JavaScript
Tutorials:
Completebeginners
JavaScriptbasics
JavaScriptfirststeps
JavaScriptbuildingblocks
IntroducingJavaScriptobjects
JavaScriptGuide
Introduction
Grammarandtypes
Controlflowanderrorhandling
Loopsanditeration
Functions
Expressionsandoperators
Numbersanddates
Textformatting
Regularexpressions
Indexedcollections
Keyedcollections
Workingwithobjects
Detailsoftheobjectmodel
Usingpromises
Iteratorsandgenerators
Metaprogramming
JavaScriptmodules
Intermediate
Client-sideJavaScriptframeworks
Client-sidewebAPIs
Are-introductiontoJavaScript
JavaScriptdatastructures
Equalitycomparisonsandsameness
Closures
Advanced
Inheritanceandtheprototypechain
Strictmode
JavaScripttypedarrays
MemoryManagement
ConcurrencymodelandEventLoop
References:
Built-inobjects
AggregateErrorArrayArrayBufferAsyncFunctionAtomicsBigIntBigInt64ArrayBigUint64ArrayBooleanDataViewDatedecodeURI()decodeURIComponent()encodeURI()encodeURIComponent()Error
Deprecated
escape()eval()EvalErrorFinalizationRegistryFloat32ArrayFloat64ArrayFunctionGeneratorGeneratorFunctionglobalThisInfinityInt16ArrayInt32ArrayInt8ArrayInternalErrorIntlisFinite()isNaN()JSONMapMathNaNNumberObjectparseFloat()parseInt()PromiseProxyRangeErrorReferenceErrorReflectRegExpSetSharedArrayBufferStringSymbolSyntaxErrorTypedArrayTypeErrorUint16ArrayUint32ArrayUint8ArrayUint8ClampedArrayundefined
Deprecated
unescape()URIErrorWeakMapWeakRefWeakSetWebAssembly
Expressions&operators
Addition(+)Additionassignment(+=)Assignment(=)asyncfunctionexpressionawaitBitwiseAND(&)BitwiseANDassignment(&=)BitwiseNOT(~)BitwiseOR(|)BitwiseORassignment(|=)BitwiseXOR(^)BitwiseXORassignment(^=)classexpressionCommaoperator(,)Conditional(ternary)operatorDecrement(--)deleteoperatorDestructuringassignmentDivision(/)Divisionassignment(/=)Equality(==)Exponentiation(**)Exponentiationassignment(**=)Functionexpressionfunction*expressionGreaterthan(>)Greaterthanorequal(>=)Groupingoperator()importimport.metainoperatorIncrement(++)Inequality(!=)instanceofLeftshift(<>)Rightshiftassignment(>>=)Spreadsyntax(...)Strictequality(===)Strictinequality(!==)Subtraction(-)Subtractionassignment(-=)superthistypeofUnarynegation(-)Unaryplus(+)Unsignedrightshift(>>>)Unsignedrightshiftassignment(>>>=)voidoperatoryieldyield*
Statements&declarations
asyncfunctionblockbreakclassconstcontinuedebuggerdo...whileemptyexportforforawait...offor...infor...offunctiondeclarationfunction*if...elseimportlabelletreturnswitchthrowtry...catchvarwhile
Deprecated
with
Functions
TheargumentsobjectArrowfunctionexpressionsDefaultparametersgetterMethoddefinitionsRestparameterssetter
Classes
ClassstaticinitializationblocksconstructorextendsPrivateclassfeaturesPublicclassfieldsstatic
Errors
Warning:-file-isbeingassigneda//#sourceMappingURL,butalreadyhasoneTypeError:invalidArray.prototype.sortargumentWarning:08/09isnotalegalECMA-262octalconstantRangeError:radixmustbeanintegerSyntaxError:invalidregularexpressionflag"x"SyntaxError:returnnotinfunctionRangeError:BigIntdivisionbyzeroRangeError:BigIntnegativeexponentTypeError:X.prototype.ycalledonincompatibletypeReferenceError:can'taccesslexicaldeclaration'X'beforeinitializationTypeError:can'taccessproperty"x"of"y"TypeError:can'tassigntoproperty"x"on"y":notanobjectRangeError:xcan'tbeconvertedtoBigIntbecauseitisn'tanintegerTypeError:can'tconvertBigInttonumberTypeError:can'tconvertxtoBigIntTypeError:can'tdefineproperty"x":"obj"isnotextensibleTypeError:property"x"isnon-configurableandcan'tbedeletedTypeError:can'tredefinenon-configurableproperty"x"TypeError:cyclicobjectvalueTypeError:can'taccessdeadobjectSyntaxError:applyingthe'delete'operatortoanunqualifiednameisdeprecatedReferenceError:deprecatedcallerorargumentsusageWarning:expressionclosuresaredeprecatedSyntaxError:"0"-prefixedoctalliteralsandoctalescapeseq.aredeprecatedSyntaxError:Using//@toindicatesourceURLpragmasisdeprecated.Use//#insteadWarning:String.xisdeprecated;useString.prototype.xinsteadWarning:Date.prototype.toLocaleFormatisdeprecatedSyntaxError:testforequality(==)mistypedasassignment(=)?TypeError:settinggetter-onlyproperty"x"SyntaxError:Unexpected'#'usedoutsideofclassbodySyntaxError:identifierstartsimmediatelyafternumericliteralSyntaxError:illegalcharacterTypeError:cannotuse'in'operatortosearchfor'x'in'y'RangeError:invalidarraylengthReferenceError:invalidassignmentleft-handsideSyntaxError:invalidBigIntsyntaxTypeError:invalidassignmenttoconst"x"RangeError:invaliddateSyntaxError:for-inloopheaddeclarationsmaynothaveinitializersSyntaxError:adeclarationintheheadofafor-ofloopcan'thaveaninitializerTypeError:invalid'instanceof'operand'x'TypeError:'x'isnotiterableSyntaxError:JSON.parse:badparsingSyntaxError:MalformedformalparameterURIError:malformedURIsequenceSyntaxError:missing]afterelementlistSyntaxError:missing:afterpropertyidSyntaxError:missing}afterfunctionbodySyntaxError:missing}afterpropertylistSyntaxError:missingformalparameterSyntaxError:missing=inconstdeclarationSyntaxError:missingnameafter.operatorSyntaxError:missing)afterargumentlistSyntaxError:missing)afterconditionSyntaxError:missing;beforestatementTypeError:MoreargumentsneededRangeError:repeatcountmustbenon-negativeTypeError:"x"isnotanon-nullobjectTypeError:"x"hasnopropertiesSyntaxError:missingvariablenameTypeError:can'tdeletenon-configurablearrayelementRangeError:argumentisnotavalidcodepointTypeError:"x"isnotaconstructorTypeError:"x"isnotafunctionReferenceError:"x"isnotdefinedRangeError:precisionisoutofrangeError:Permissiondeniedtoaccessproperty"x"TypeError:"x"isread-onlySyntaxError:redeclarationofformalparameter"x"TypeError:ReduceofemptyarraywithnoinitialvalueSyntaxError:"x"isareservedidentifierRangeError:repeatcountmustbelessthaninfinityWarning:unreachablecodeafterreturnstatementSyntaxError:"usestrict"notallowedinfunctionwithnon-simpleparametersInternalError:toomuchrecursionReferenceError:assignmenttoundeclaredvariable"x"ReferenceError:referencetoundefinedproperty"x"SyntaxError:UnexpectedtokenTypeError:"x"is(not)"y"SyntaxError:functionstatementrequiresanameSyntaxError:unterminatedstringliteral
Misc
JavaScripttechnologiesoverview
Lexicalgrammar
JavaScriptdatastructures
Enumerabilityandownershipofproperties
Iterationprotocols
Strictmode
Transitioningtostrictmode
Templateliterals
Deprecatedfeatures
CharacterclassesAssertionsGroupsandbackreferencesQuantifiersUnicodepropertyescapesRegularexpressionsyntaxcheatsheetThispageprovidesanoverallcheatsheetofallthecapabilitiesofRegExpsyntaxbyaggregatingthecontentofthearticlesintheRegExpguide.Ifyouneedmoreinformationonaspecifictopic,pleasefollowthelinkonthecorrespondingheadingtoaccessthefullarticleorheadtotheguide.CharacterclassesCharacterclassesdistinguishkindsofcharacterssuchas,forexample,distinguishingbetweenlettersanddigits.
Characters
Meaning
[xyz][a-c]
Acharacterclass.Matchesanyoneoftheenclosedcharacters.Youcan
specifyarangeofcharactersbyusingahyphen,butifthehyphen
appearsasthefirstorlastcharacterenclosedinthesquarebrackets,
itistakenasaliteralhyphentobeincludedinthecharacterclass
asanormalcharacter.
Forexample,[abcd]isthesameas[a-d].
Theymatchthe"b"in"brisket",andthe"a"orthe"c"in"arch",
butnotthe"-"(hyphen)in"non-profit".
Forexample,[abcd-]and[-abcd]matchthe
"b"in"brisket",the"a"orthe"c"in"arch",andthe"-"(hyphen)
in"non-profit".
Forexample,[\w-]isthesameas
[A-Za-z0-9_-].Theybothmatchanyofthecharactersin
"[email protected]"exceptforthe"@"andthe".".
[^xyz][^a-c]
Anegatedorcomplementedcharacterclass.Thatis,itmatches
anythingthatisnotenclosedinthebrackets.Youcanspecifyarange
ofcharactersbyusingahyphen,butifthehyphenappearsasthe
firstorlastcharacterenclosedinthesquarebrackets,itistakenas
aliteralhyphentobeincludedinthecharacterclassasanormal
character.Forexample,[^abc]isthesameas
[^a-c].Theyinitiallymatch"o"in"bacon"and"h"in
"chop".
Note:The^charactermayalsoindicatethe
beginningofinput.
.
Hasoneofthefollowingmeanings:
Matchesanysinglecharacterexceptlineterminators:
\n,\r,\u2028or
\u2029.Forexample,/.y/matches"my"and
"ay",butnot"yes",in"yesmakemyday".
Insideacharacterclass,thedotlosesitsspecialmeaningand
matchesaliteraldot.
Notethatthemmultilineflagdoesn'tchangethedot
behavior.Sotomatchapatternacrossmultiplelines,thecharacter
class[^]canbeused—itwillmatchanycharacter
includingnewlines.
ES2018addedthes"dotAll"flag,whichallowsthedotto
alsomatchlineterminators.
\d
Matchesanydigit(Arabicnumeral).Equivalentto[0-9].
Forexample,/\d/or/[0-9]/matches"2"in
"B2isthesuitenumber".
\D
Matchesanycharacterthatisnotadigit(Arabicnumeral).Equivalent
to[^0-9].Forexample,/\D/or
/[^0-9]/matches"B"in"B2isthesuitenumber".
\w
MatchesanyalphanumericcharacterfromthebasicLatinalphabet,
includingtheunderscore.Equivalentto[A-Za-z0-9_].For
example,/\w/matches"a"in"apple","5"in"$5.28",and
"3"in"3D".
\W
Matchesanycharacterthatisnotawordcharacterfromthebasic
Latinalphabet.Equivalentto[^A-Za-z0-9_].Forexample,
/\W/or/[^A-Za-z0-9_]/matches"%"in
"50%".
\s
Matchesasinglewhitespacecharacter,includingspace,tab,form
feed,linefeed,andotherUnicodespaces.Equivalentto
[
\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].Forexample,/\s\w*/matches"bar"in"foobar".
\S
Matchesasinglecharacterotherthanwhitespace.Equivalentto
[^
\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].Forexample,/\S\w*/matches"foo"in"foobar".
\t
Matchesahorizontaltab.
\r
Matchesacarriagereturn.
\n
Matchesalinefeed.
\v
Matchesaverticaltab.
\f
Matchesaform-feed.
[\b]
Matchesabackspace.Ifyou'relookingfortheword-boundarycharacter
(\b),see
Boundaries.
\0
MatchesaNULcharacter.Donotfollowthiswithanotherdigit.
\cX
Matchesacontrolcharacterusing
caretnotation,where"X"isaletterfromA–Z(correspondingtocodepoints
U+0001–U+001F).Forexample,
/\cM/matches"\r"in"\r\n".
\xhh
Matchesthecharacterwiththecodehh(two
hexadecimaldigits).
\uhhhh
MatchesaUTF-16code-unitwiththevalue
hhhh(fourhexadecimaldigits).
\u{hhhh}or\u{hhhhh}
(Onlywhentheuflagisset.)Matchesthecharacterwith
theUnicodevalueU+hhhhorU+hhhhh
(hexadecimaldigits).
\
Indicatesthatthefollowingcharactershouldbetreatedspecially,or
"escaped".Itbehavesoneoftwoways.
Forcharactersthatareusuallytreatedliterally,indicatesthat
thenextcharacterisspecialandnottobeinterpretedliterally.
Forexample,/b/matchesthecharacter"b".Byplacing
abackslashinfrontof"b",thatisbyusing/\b/,the
characterbecomesspecialtomeanmatchawordboundary.
Forcharactersthatareusuallytreatedspecially,indicatesthat
thenextcharacterisnotspecialandshouldbeinterpreted
literally.Forexample,"*"isaspecialcharacterthatmeans0or
moreoccurrencesoftheprecedingcharactershouldbematched;for
example,/a*/meansmatch0ormore"a"s.Tomatch
*literally,precedeitwithabackslash;forexample,
/a\*/matches"a*".
Notethatsomecharacterslike:,-,
@,etc.neitherhaveaspecialmeaningwhenescapednor
whenunescaped.Escapesequenceslike\:,
\-,\@willbeequivalenttotheirliteral,
unescapedcharacterequivalentsinregularexpressions.However,in
regularexpressionswiththe
unicodeflag,thesewillcauseaninvalididentityescapeerror.Thisis
donetoensurebackwardcompatibilitywithexistingcodethatusesnew
escapesequenceslike\por\k.
Note:Tomatchthischaracterliterally,escapeit
withitself.Inotherwordstosearchfor\use
/\\/.
x|y
Disjunction:Matcheseither"x"or"y".Eachcomponent,separatedbyapipe(|),iscalledanalternative.Forexample,
/green|red/matches"green"in"greenapple"and"red"in
"redapple".
Note:Adisjunctionisanotherwaytospecify"asetofchoices",butit'snotacharacterclass.Disjunctionsarenotatoms—youneedtouseagrouptomakeitpartofabiggerpattern.[abc]isfunctionallyequivalentto(?:a|b|c).
AssertionsAssertionsincludeboundaries,whichindicatethebeginningsandendingsoflinesandwords,andotherpatternsindicatinginsomewaythatamatchispossible(includinglook-ahead,look-behind,andconditionalexpressions).Boundary-typeassertions
Characters
Meaning
^
Matchesthebeginningofinput.Ifthemultilineflagissettotrue,
alsomatchesimmediatelyafteralinebreakcharacter.Forexample,
/^A/doesnotmatchthe"A"in"anA",butdoesmatchthe
first"A"in"AnA".
Note:Thischaracterhasadifferentmeaningwhen
itappearsatthestartofa
characterclass.
$
Matchestheendofinput.Ifthemultilineflagissettotrue,also
matchesimmediatelybeforealinebreakcharacter.Forexample,
/t$/doesnotmatchthe"t"in"eater",butdoesmatchit
in"eat".
\b
Matchesawordboundary.Thisisthepositionwhereawordcharacter
isnotfollowedorprecededbyanotherword-character,suchasbetween
aletterandaspace.Notethatamatchedwordboundaryisnot
includedinthematch.Inotherwords,thelengthofamatchedword
boundaryiszero.
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"is
theendofthestring,thusnotfollowedbyawordcharacter.
/\w\b\w/willnevermatchanything,becauseaword
charactercanneverbefollowedbybothanon-wordandaword
character.
Tomatchabackspacecharacter([\b]),see
CharacterClasses.
\B
Matchesanon-wordboundary.Thisisapositionwherethepreviousand
nextcharacterareofthesametype:Eitherbothmustbewords,or
bothmustbenon-words,forexamplebetweentwolettersorbetweentwo
spaces.Thebeginningandendofastringareconsiderednon-words.
Sameasthematchedwordboundary,thematchednon-wordboundaryis
alsonotincludedinthematch.Forexample,
/\Bon/matches"on"in"atnoon",and
/ye\B/matches"ye"in"possiblyyesterday".
Otherassertions
Note:The?charactermayalsobeusedasaquantifier.
Characters
Meaning
x(?=y)
Lookaheadassertion:Matches"x"onlyif"x"is
followedby"y".Forexample,/Jack(?=Sprat)/matches
"Jack"onlyifitisfollowedby"Sprat"./Jack(?=Sprat|Frost)/
matches"Jack"onlyifitisfollowedby"Sprat"or"Frost".However,
neither"Sprat"nor"Frost"ispartofthematchresults.
x(?!y)
Negativelookaheadassertion:Matches"x"onlyif"x"
isnotfollowedby"y".Forexample,/\d+(?!\.)/matches
anumberonlyifitisnotfollowedbyadecimalpoint./\d+(?!\.)/.exec('3.141')
matches"141"butnot"3".
(?<=y)x
Lookbehindassertion:Matches"x"onlyif"x"is
precededby"y".Forexample,
/(?<=Jack)Sprat/matches"Sprat"onlyifitis
precededby"Jack"./(?<=Jack|Tom)Sprat/matches
"Sprat"onlyifitisprecededby"Jack"or"Tom".However,neither
"Jack"nor"Tom"ispartofthematchresults.
(?x)
Namedcapturinggroup:Matches"x"andstoresiton
thegroupspropertyofthereturnedmatchesunderthenamespecified
by
延伸文章資訊
- 1regexp cheatsheet - Devhints
Basic cheatsheets for regular expression · One-page guide to regexp.
- 2Work with strings with stringr : : CHEAT SHEET - GitLab
Work with strings with stringr : : CHEAT SHEET. Detect Matches ... regexp matches example a? zero...
- 3RegExLib.com Regular Expression Cheat Sheet (.NET)
RegExLib.com Regular Expression Cheat Sheet (.NET). Metacharacters Defined. MChar, Definition. ^,...
- 4Regular Expressions Cheat Sheet by DaveChild
A quick reference guide for regular expressions (regex), including symbols, ranges, grouping, ass...
- 5Regular Expressions cheat sheet
Regular Expressions cheat sheet. Basic matching. Each symbol matches a single character: anything...