RegExp - JavaScript - MDN Web Docs - Mozilla

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

Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it ... SkiptomaincontentSkiptosearchSkiptoselectlanguage給開發者的網頁技術文件JavaScriptJavaScript參考文件標準內建物件RegExpArticleActions正體中文(繁體)ThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity.說明ConstructorPropertiesMethodsRegExpprototypeobjectsandinstancesExamplesSpecificationsBrowsercompatibilitySeealsoRelatedTopicsStandardbuilt-inobjectsRegExpPropertiesgetRegExp[@@species](en-US)RegExp.prototype.dotAll(en-US)RegExp.prototype.flags(en-US)RegExp.prototype.global(en-US)RegExp.prototype.hasIndices(en-US)RegExp.prototype.ignoreCase(en-US) Non-Standard RegExp.input($_)(en-US)RegExp:lastIndex(en-US) Non-Standard RegExp.lastMatch($&)(en-US) Non-Standard RegExp.lastParen($+)(en-US) Non-Standard RegExp.leftContext($`)(en-US)RegExp.prototype.multiline(en-US) Non-Standard RegExp.$1-$9(en-US) Non-Standard RegExp.rightContext($')(en-US)RegExp.prototype.source(en-US)RegExp.prototype.sticky(en-US)RegExp.prototype.unicode(en-US)MethodsRegExp.prototype[@@match]()(en-US)RegExp.prototype[@@matchAll]()(en-US)RegExp.prototype[@@replace]()(en-US)RegExp.prototype[@@search]()(en-US)RegExp.prototype[@@split]()(en-US) Deprecated RegExp.prototype.compile()(en-US)RegExp.prototype.exec()(en-US)RegExp.prototype.test()(en-US)RegExp.prototype.toString()(en-US)Inheritance:FunctionProperties Deprecated Function.arguments(en-US) Deprecated Function.caller(en-US) Non-Standard Function.displayName(en-US)Function.lengthFunction.name(en-US)MethodsFunction.prototype.apply()Function.prototype.bind()Function.prototype.call()Function.prototype.toString()(en-US)ObjectPropertiesObject.prototype.constructor(en-US) Deprecated Object.prototype.__proto__Methods Deprecated Object.prototype.__defineGetter__()(en-US) Deprecated Object.prototype.__defineSetter__()(en-US) Deprecated Object.prototype.__lookupGetter__()(en-US) Deprecated Object.prototype.__lookupSetter__()(en-US)Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()(en-US)Object.prototype.propertyIsEnumerable()(en-US)Object.setPrototypeOf()(en-US)Object.prototype.toLocaleString()(en-US)Object.prototype.toString()(en-US)Object.prototype.valueOf()(en-US)說明ConstructorPropertiesMethodsRegExpprototypeobjectsandinstancesExamplesSpecificationsBrowsercompatibilitySeealsoRegExp RegExp物件被用來比對符合自訂規則的文字。

關於正規表達式(regularexpressions)的介紹,可以閱讀JavaScript指南中的正規表達式章節。

說明建立RegExp物件有兩種方式:文字表示法(literalnotation)和建構子(constructor)。

文字表示法的參數,頭尾以斜線標註,且不使用引號標註。

建構子函式的參數,頭尾不以斜線標註,但使用引號標註。

以下的表達式會建立出相同的正規表達式: /ab+c/i newRegExp(/ab+c/,'i')//literalnotation newRegExp('ab+c','i')//constructor Theliteralnotationprovidesacompilationoftheregularexpressionwhentheexpressionisevaluated.Useliteralnotationwhentheregularexpressionwillremainconstant.Forexample,ifyouuseliteralnotationtoconstructaregularexpressionusedinaloop,theregularexpressionwon'tberecompiledoneachiteration. Theconstructoroftheregularexpressionobject—forexample,newRegExp('ab+c')—providesruntimecompilationoftheregularexpression.Usetheconstructorfunctionwhenyouknowtheregularexpressionpatternwillbechanging,oryoudon'tknowthepatternandaregettingitfromanothersource,suchasuserinput. StartingwithECMAScript6,newRegExp(/ab+c/,'i')nolongerthrowsaTypeError("can'tsupplyflagswhenconstructingoneRegExpfromanother")whenthefirstargumentisaRegExpandthesecondflagsargumentispresent.AnewRegExpfromtheargumentsiscreatedinstead. Whenusingtheconstructorfunction,thenormalstringescaperules(precedingspecialcharacterswith\whenincludedinastring)arenecessary. Forexample,thefollowingareequivalent: letre=/\w+/ letre=newRegExp('\\w+') Constructor RegExp() Createsaregularexpressionobject. Properties RegExp.prototype Allowstheadditionofpropertiestoallobjects. RegExp.length ThevalueofRegExp.lengthis2. getRegExp[@@species](en-US) Theconstructorfunctionthatisusedtocreatederivedobjects. RegExp.lastIndex(en-US) Theindexatwhichtostartthenextmatch. MethodsTheglobalRegExpobjecthasnomethodsofitsown.However,itdoesinheritsomemethodsthroughtheprototypechain.RegExpprototypeobjectsandinstancesProperties SeealsodeprecatedRegExpproperties. NotethatseveraloftheRegExppropertieshavebothlongandshort(Perl-like)names.Bothnamesalwaysrefertothesamevalue.PerlistheprogramminglanguagefromwhichJavaScriptmodeleditsregularexpressions. RegExp.prototype.constructor Specifiesthefunctionthatcreatesanobject'sprototype. RegExp.prototype.flags(en-US) AstringthatcontainstheflagsoftheRegExpobject. RegExp.prototype.dotAll(en-US) Whether.matchesnewlinesornot. RegExp.prototype.global(en-US) Whethertotesttheregularexpressionagainstallpossiblematchesinastring,oronlyagainstthefirst. RegExp.prototype.ignoreCase(en-US) Whethertoignorecasewhileattemptingamatchinastring. RegExp.prototype.multiline(en-US) Whetherornottosearchinstringsacrossmultiplelines. RegExp.prototype.source(en-US) Thetextofthepattern. RegExp.prototype.sticky(en-US) Whetherornotthesearchissticky. RegExp.prototype.unicode(en-US) WhetherornotUnicodefeaturesareenabled. Methods RegExp.prototype.compile()(en-US) (Re-)compilesaregularexpressionduringexecutionofascript. RegExp.prototype.exec()(en-US) Executesasearchforamatchinitsstringparameter. RegExp.prototype.test()(en-US) Testsforamatchinitsstringparameter. RegExp.prototype[@@match]()(en-US) Performsmatchtogivenstringandreturnsmatchresult. RegExp.prototype[@@matchAll]()(en-US) Returnsallmatchesoftheregularexpressionagainstastring. RegExp.prototype[@@replace]()(en-US) Replacesmatchesingivenstringwithnewsubstring. RegExp.prototype[@@search]()(en-US) Searchesthematchingivenstringandreturnstheindexthepatternfoundinthestring. RegExp.prototype[@@split]()(en-US) Splitsgivenstringintoanarraybyseparatingthestringintosubstring. RegExp.prototype.toSource()(en-US) Returnsanobjectliteralrepresentingthespecifiedobject;youcanusethisvaluetocreateanewobject.OverridestheObject.prototype.toSource()(en-US)method. RegExp.prototype.toString()(en-US) Returnsastringrepresentingthespecifiedobject.OverridestheObject.prototype.toString()(en-US)method. ExamplesUsingaregularexpressiontochangedataformatThefollowingscriptusesthereplace()methodoftheStringinstancetomatchanameintheformatfirstlastandoutputitintheformatlast,first. Inthereplacementtext,thescriptuses$1and$2toindicatetheresultsofthecorrespondingmatchingparenthesesintheregularexpressionpattern. letre=/(\w+)\s(\w+)/ letstr='JohnSmith' letnewstr=str.replace(re,'$2,$1') console.log(newstr) Thisdisplays"Smith,John".Usingregularexpressiontosplitlineswithdifferentlineendings/endsofline/linebreaksThedefaultlineendingvariesdependingontheplatform(Unix,Windows,etc.).Thelinesplittingprovidedinthisexampleworksonallplatforms. lettext='Sometext\nAndsomemore\r\nAndyet\rThisistheend' letlines=text.split(/\r\n|\r|\n/) console.log(lines)//logs['Sometext','Andsomemore','Andyet','Thisistheend'] Notethattheorderofthepatternsintheregularexpressionmatters.Usingregularexpressiononmultiplelineslets='Pleaseyes\nmakemyday!' s.match(/yes.*day/); //Returnsnull s.match(/yes[^]*day/); //Returns["yes\nmakemyday"] UsingaregularexpressionwiththestickyflagThestickyflagindicatesthattheregularexpressionperformsstickymatchinginthetargetstringbyattemptingtomatchstartingatRegExp.prototype.lastIndex(en-US). letstr='#foo#' letregex=/foo/y regex.lastIndex=1 regex.test(str)//true regex.lastIndex=5 regex.test(str)//false(lastIndexistakenintoaccountwithstickyflag) regex.lastIndex//0(resetaftermatchfailure)ThedifferencebetweenthestickyflagandtheglobalflagWiththestickyflagy,thenextmatchhastohappenatthelastIndexposition,whilewiththeglobalflagg,thematchcanhappenatthelastIndexpositionorlater: re=/\d/y; while(r=re.exec("123456"))console.log(r,"ANDre.lastIndex",re.lastIndex); //['1',index:0,input:'123456',groups:undefined]ANDre.lastIndex1 //['2',index:1,input:'123456',groups:undefined]ANDre.lastIndex2 //['3',index:2,input:'123456',groups:undefined]ANDre.lastIndex3 //...andnomorematch. Withtheglobalflagg,all6digitswouldbematched,notjust3.RegularexpressionandUnicodecharactersAsmentionedabove,\wor\WonlymatchesASCIIbasedcharacters;forexample,atoz,AtoZ,0to9,and_. TomatchcharactersfromotherlanguagessuchasCyrillicorHebrew,use\uhhhh,wherehhhhisthecharacter'sUnicodevalueinhexadecimal. ThisexampledemonstrateshowonecanseparateoutUnicodecharactersfromaword. lettext='Образецtextнарусскомязыке' letregex=/[\u0400-\u04FF]+/g letmatch=regex.exec(text) console.log(match[0])//logs'Образец' console.log(regex.lastIndex)//logs'7' letmatch2=regex.exec(text) console.log(match2[0])//logs'на'[didnotlog'text'] console.log(regex.lastIndex)//logs'15' //andsoon TheUnicodepropertyescapesfeatureintroducesasolution,byallowingforastatementassimpleas\p{scx=Cyrl}.OnecanalsouseanexternalresourceforgettingthecompleteUnicodeblockrangefordifferentscripts,suchasRegexp-Unicode-block.Extractingsub-domainnamefromURLleturl='http://xxx.domain.com' console.log(/[^.]+/.exec(url)[0].substr(7))//logs'xxx' SpecificationsSpecificationECMAScriptLanguageSpecification#sec-regexp-regular-expression-objectsBrowsercompatibilityBCDtablesonlyloadinthebrowser Firefox-specificnotesStartingwithFirefox34,inthecaseofacapturinggroupwithquantifierspreventingitsexercise,thematchedtextforacapturinggroupisnowundefinedinsteadofanemptystring: //Firefox33orolder 'x'.replace(/x(.)?/g,function(m,group){ console.log("'group:"+group+"'"); }); //'group:' //Firefox34ornewer 'x'.replace(/x(.)?/g,function(m,group){ console.log("'group:"+group+"'"); }); //'group:undefined' Notethatduetowebcompatibility,RegExp.$Nwillstillreturnanemptystringinsteadofundefined(bug1053944).Seealso RegularExpressionschapterintheJavaScriptGuide String.prototype.match() String.prototype.replace() Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:2022年6月30日,byMDNcontributors



請為這篇文章評分?