Regular expression syntax cheatsheet - JavaScript | MDN

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

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.Theanglebrackets(< and>)arerequiredforgroupname. Forexample,toextracttheUnitedStatesareacodefromaphone number,wecoulduse/\((?\d\d\d)\)/.The resultingnumberwouldappearundermatches.groups.area. (?:x) Non-capturinggroup:Matches"x"butdoesnotremember thematch.Thematchedsubstringcannotberecalledfromtheresulting array'selements([1],...,[n])orfromthepredefined RegExpobject'sproperties($1,...,$9). \n Where"n"isapositiveinteger.Abackreferencetothelast substringmatchingthenparentheticalintheregularexpression (countingleftparentheses).Forexample, /apple(,)\sorange\1/matches"apple,orange,"in"apple, orange,cherry,peach". \k AbackreferencetothelastsubstringmatchingtheNamedcapturegroupspecifiedby. Forexample,/(?\w+),yes\k<title>/matches"Sir,yesSir"in"Doyoucopy?Sir,yesSir!". Note:\kisusedliterallyhereto indicatethebeginningofabackreferencetoaNamedcapturegroup. QuantifiersQuantifiersindicatenumbersofcharactersorexpressionstomatch. Note:Inthefollowing,itemrefersnotonlytosingularcharacters,butalsoincludescharacterclasses,Unicodepropertyescapes,groupsandbackreferences. Characters Meaning x* Matchestheprecedingitem"x"0ormoretimes.Forexample, /bo*/matches"boooo"in"Aghostbooooed"and"b"in"A birdwarbled",butnothingin"Agoatgrunted". x+ Matchestheprecedingitem"x"1ormoretimes.Equivalentto {1,}.Forexample,/a+/matchesthe"a"in "candy"andallthe"a"'sin"caaaaaaandy". x? Matchestheprecedingitem"x"0or1times.Forexample, /e?le?/matchesthe"el"in"angel"andthe"le"in "angle." Ifusedimmediatelyafteranyofthequantifiers*, +,?,or{},makesthe quantifiernon-greedy(matchingtheminimumnumberoftimes),as opposedtothedefault,whichisgreedy(matchingthemaximumnumber oftimes). x{n} Where"n"isapositiveinteger,matchesexactly"n"occurrencesof theprecedingitem"x".Forexample,/a{2}/doesn'tmatch the"a"in"candy",butitmatchesallofthe"a"'sin"caandy",and thefirsttwo"a"'sin"caaandy". x{n,} Where"n"isapositiveinteger,matchesatleast"n"occurrencesof theprecedingitem"x".Forexample,/a{2,}/doesn't matchthe"a"in"candy",butmatchesallofthea'sin"caandy"and in"caaaaaaandy". x{n,m} Where"n"is0orapositiveinteger,"m"isapositiveinteger,and m>n,matchesatleast"n"andatmost"m"occurrencesofthepreceding item"x".Forexample,/a{1,3}/matchesnothingin "cndy",the"a"in"candy",thetwo"a"'sin"caandy",andthefirst three"a"'sin"caaaaaaandy".Noticethatwhenmatching"caaaaaaandy", thematchis"aaa",eventhoughtheoriginalstringhadmore"a"sin it. x*?x+?x??x{n}?x{n,}?x{n,m}? Bydefaultquantifierslike*and+are "greedy",meaningthattheytrytomatchasmuchofthestringas possible.The?characterafterthequantifiermakesthe quantifier"non-greedy":meaningthatitwillstopassoonasitfinds amatch.Forexample,givenastringlike"some<foo><bar> new</bar></foo>thing": /<.>/willmatch"<foo><bar>new </bar></foo>" /<.>/willmatch"<foo>" UnicodepropertyescapesUnicodepropertyescapesallowformatchingcharactersbasedontheirUnicodeproperties. //Non-binaryvalues \p{UnicodePropertyValue} \p{UnicodePropertyName=UnicodePropertyValue} //Binaryandnon-binaryvalues \p{UnicodeBinaryPropertyName} //Negation:\Pisnegated\p \P{UnicodePropertyValue} \P{UnicodeBinaryPropertyName} UnicodeBinaryPropertyName Thenameofabinaryproperty.E.g.:ASCII,Alpha,Math,Diacritic,Emoji,Hex_Digit,Math,White_space,etc.SeeUnicodeDataPropList.txtformoreinfo. UnicodePropertyName Thenameofanon-binaryproperty: General_Category(gc) Script(sc) Script_Extensions(scx) SeealsoPropertyValueAliases.txt UnicodePropertyValue OneofthetokenslistedintheValuessection,below.Manyvalueshavealiasesorshorthand(e.g.thevalueDecimal_NumberfortheGeneral_CategorypropertymaybewrittenNd,digit,orDecimal_Number).Formostvalues,theUnicodePropertyNamepartandequalssignmaybeomitted.IfaUnicodePropertyNameisspecified,thevaluemustcorrespondtothepropertytypegiven. Note:Astherearemanypropertiesandvaluesavailable,wewillnotdescribethemexhaustivelyherebutratherprovidevariousexamples Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Jul5,2022,byMDNcontributors</foo></.></.>



請為這篇文章評分?