String.prototype.match() - JavaScript - MDN Web Docs - Mozilla
文章推薦指數: 80 %
The match() method retrieves the matches when matching a string against a regular expression. Syntax. str .match( regexp ). Parameters. regexp ...
SkiptomaincontentSkiptosearchSkiptoselectlanguage給開發者的網頁技術文件JavaScriptJavaScript參考文件標準內建物件字串String.prototype.match()ArticleActions正體中文(繁體)ThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity.SyntaxDescriptionExamplesSpecificationsBrowsercompatibilityFirefox-specificnotesSeealsoRelatedTopicsStandardbuilt-inobjectsStringPropertiesStringlength(en-US)MethodsString.prototype[@@iterator]()(en-US)
Deprecated
String.prototype.anchor()(en-US)
Experimental
String.prototype.at()(en-US)
Deprecated
String.prototype.big()(en-US)
Deprecated
String.prototype.blink()(en-US)
Deprecated
String.prototype.bold()(en-US)String.prototype.charAt()(en-US)String.prototype.charCodeAt()(en-US)String.prototype.codePointAt()(en-US)String.prototype.concat()String.prototype.endsWith()(en-US)
Deprecated
String.prototype.fixed()(en-US)
Deprecated
String.prototype.fontcolor()(en-US)
Deprecated
String.prototype.fontsize()(en-US)String.fromCharCode()(en-US)String.fromCodePoint()(en-US)String.prototype.includes()(en-US)String.prototype.indexOf()(en-US)
Deprecated
String.prototype.italics()(en-US)String.prototype.lastIndexOf()(en-US)
Deprecated
String.prototype.link()(en-US)String.prototype.localeCompare()(en-US)String.prototype.match()String.prototype.matchAll()(en-US)String.prototype.normalize()(en-US)String.prototype.padEnd()(en-US)String.prototype.padStart()String.raw()(en-US)String.prototype.repeat()(en-US)String.prototype.replace()String.prototype.replaceAll()(en-US)String.prototype.search()(en-US)String.prototype.slice()(en-US)
Deprecated
String.prototype.small()(en-US)String.prototype.split()(en-US)String.prototype.startsWith()(en-US)
Deprecated
String.prototype.strike()(en-US)
Deprecated
String.prototype.sub()(en-US)
Deprecated
String.prototype.substr()(en-US)String.prototype.substring()(en-US)
Deprecated
String.prototype.sup()(en-US)String.prototype.toLocaleLowerCase()(en-US)String.prototype.toLocaleUpperCase()(en-US)String.prototype.toLowerCase()String.prototype.toString()(en-US)String.prototype.toUpperCase()(en-US)String.prototype.trim()String.prototype.trimEnd()(en-US)String.prototype.trimStart()(en-US)String.prototype.valueOf()(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)SyntaxDescriptionExamplesSpecificationsBrowsercompatibilityFirefox-specificnotesSeealsoString.prototype.match()
Thematch()methodretrievesthematcheswhenmatchingastringagainstaregularexpression.Syntaxstr.match(regexp)Parameters
regexp
一個正規表達式的物件。
若傳入一個非正規表達式的物件obj,則會視為傳入newRegExp(obj)。
若只呼叫match()而沒有傳入任何參數,則會回傳內含一個空字串的陣列,即[""]。
ReturnvalueIfthestringmatchestheexpression,itwillreturnanArraycontainingtheentirematchedstringasthefirstelement,followedbyanyresultscapturedinparentheses.Iftherewerenomatches,nullisreturned.DescriptionIftheregularexpressiondoesnotincludethegflag,str.match()willreturnthesameresultasRegExp.exec()(en-US).ThereturnedArrayhasanextrainputproperty,whichcontainstheoriginalstringthatwasparsed.Inaddition,ithasanindexproperty,whichrepresentsthezero-basedindexofthematchinthestring.
Iftheregularexpressionincludesthegflag,themethodreturnsanArraycontainingallmatchedsubstringsratherthanmatchobjects.Capturedgroupsarenotreturned.Iftherewerenomatches,themethodreturnsnull.Seealso:RegExpmethods
IfyouneedtoknowifastringmatchesaregularexpressionRegExp,useRegExp.test()(en-US).
Ifyouonlywantthefirstmatchfound,youmightwanttouseRegExp.exec()(en-US)instead.
ifyouwanttoobtaincapturegroupsandtheglobalflagisset,youneedtouseRegExp.exec()(en-US)instead.
ExamplesUsingmatch()Inthefollowingexample,match()isusedtofind'Chapter'followedby1ormorenumericcharactersfollowedbyadecimalpointandnumericcharacter0ormoretimes.Theregularexpressionincludestheiflagsothatupper/lowercasedifferenceswillbeignored.
varstr='Formoreinformation,seeChapter3.4.5.1';
varre=/see(chapter\d+(\.\d)*)/i;
varfound=str.match(re);
console.log(found);
//logs['seeChapter3.4.5.1',
//'Chapter3.4.5.1',
//'.1',
//index:22,
//input:'Formoreinformation,seeChapter3.4.5.1']
//'seeChapter3.4.5.1'isthewholematch.
//'Chapter3.4.5.1'wascapturedby'(chapter\d+(\.\d)*)'.
//'.1'wasthelastvaluecapturedby'(\.\d)'.
//The'index'property(22)isthezero-basedindexofthewholematch.
//The'input'propertyistheoriginalstringthatwasparsed.Usingglobalandignorecaseflagswithmatch()Thefollowingexampledemonstratestheuseoftheglobalandignorecaseflagswithmatch().AlllettersAthroughEandathroughearereturned,eachitsownelementinthearray.
varstr='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
varregexp=/[A-E]/gi;
varmatches_array=str.match(regexp);
console.log(matches_array);
//['A','B','C','D','E','a','b','c','d','e']
Usingmatch()withnoparametervarstr="Nothingwillcomeofnothing.";
str.match();//returns[""]Anon-RegExpobjectastheparameterWhentheparameterisastringoranumber,itisimplicitlyconvertedtoaRegExpbyusingnewRegExp(obj).Ifitisapositivenumberwithapositivesign,theRegExp()methodwillignorethepositivesign.
varstr1="NaNmeansnotanumber.Infinitycontains-Infinityand+InfinityinJavaScript.",
str2="Mygrandfatheris65yearsoldandMygrandmotheris63yearsold.",
str3="Thecontractwasdeclarednullandvoid.";
str1.match("number");//"number"isastring.returns["number"]
str1.match(NaN);//thetypeofNaNisthenumber.returns["NaN"]
str1.match(Infinity);//thetypeofInfinityisthenumber.returns["Infinity"]
str1.match(+Infinity);//returns["Infinity"]
str1.match(-Infinity);//returns["-Infinity"]
str2.match(65);//returns["65"]
str2.match(+65);//Anumberwithapositivesign.returns["65"]
str3.match(null);//returns["null"]SpecificationsSpecificationECMAScriptLanguageSpecification#sec-string.prototype.matchBrowsercompatibilityBCDtablesonlyloadinthebrowserFirefox-specificnotes
flagswasanonstandardsecondargumentonlyavailableinGecko:str.match(regexp,flags)
StartingwithGecko27(Firefox27/Thunderbird27/SeaMonkey2.24),thismethodhasbeenadjustedtoconformwiththeECMAScriptspecification.Whenmatch()iscalledwithaglobalregularexpression,theRegExp.lastIndex(en-US)property(ifspecified)willberesetto0(bug 501739).
StartingwithGecko39(Firefox39/Thunderbird39/SeaMonkey2.36),thenon-standardflagsargumentisdeprecatedandthrowsaconsolewarning(bug 1142351).
StartingwithGecko47(Firefox47/Thunderbird47/SeaMonkey2.44),thenon-standardflagsargumentisnolongersupportedinnon-releasebuildsandwillsoonberemovedentirely(bug 1245801).
StartingwithGecko49(Firefox49/Thunderbird49/SeaMonkey2.46),thenon-standardflagsargumentisnolongersupported(bug 1108382).
Seealso
RegExp
RegExp.prototype.exec()(en-US)
RegExp.prototype.test()(en-US)
Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:2022年6月30日,byMDNcontributors
延伸文章資訊
- 14.8 Regular Expressions - Racket Documentation
If a character regexp is used with a byte string or input port, it matches UTF-8 encodings (see E...
- 2regex101: build, test, and debug regex
Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python...
- 3Guide to Regular Expressions and Matching Strings in JavaScript
- 4Simple RegEx Tutorial
Regular Expression can be used in Content Filter conditions. ... a string that starts and ends wi...
- 5Regex – Match Any Character(s) - HowToDoInJava