Regex.Match Method (System.Text.RegularExpressions)

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

Searches an input string for a substring that matches a regular expression pattern and returns the first occurrence as a single Match object. Skiptomaincontent Thisbrowserisnolongersupported. UpgradetoMicrosoftEdgetotakeadvantageofthelatestfeatures,securityupdates,andtechnicalsupport. DownloadMicrosoftEdge Moreinfo Tableofcontents Exitfocusmode Language ReadinEnglish Save Tableofcontents ReadinEnglish Save Edit Twitter LinkedIn Facebook Email Tableofcontents Regex.MatchMethod Reference Definition Namespace: System.Text.RegularExpressions Assembly:System.Text.RegularExpressions.dll Assembly:System.dll Assembly:netstandard.dll Important Someinformationrelatestoprereleaseproductthatmaybesubstantiallymodifiedbeforeit’sreleased.Microsoftmakesnowarranties,expressorimplied,withrespecttotheinformationprovidedhere. SearchesaninputstringforasubstringthatmatchesaregularexpressionpatternandreturnsthefirstoccurrenceasasingleMatchobject. Inthisarticle Overloads Match(String,String,RegexOptions,TimeSpan) Searchestheinputstringforthefirstoccurrenceofthespecifiedregularexpression,usingthespecifiedmatchingoptionsandtime-outinterval. Match(String) SearchesthespecifiedinputstringforthefirstoccurrenceoftheregularexpressionspecifiedintheRegexconstructor. Match(String,Int32) Searchestheinputstringforthefirstoccurrenceofaregularexpression,beginningatthespecifiedstartingpositioninthestring. Match(String,String) Searchesthespecifiedinputstringforthefirstoccurrenceofthespecifiedregularexpression. Match(String,Int32,Int32) Searchestheinputstringforthefirstoccurrenceofaregularexpression,beginningatthespecifiedstartingpositionandsearchingonlythespecifiednumberofcharacters. Match(String,String,RegexOptions) Searchestheinputstringforthefirstoccurrenceofthespecifiedregularexpression,usingthespecifiedmatchingoptions. Match(String,String,RegexOptions,TimeSpan) Searchestheinputstringforthefirstoccurrenceofthespecifiedregularexpression,usingthespecifiedmatchingoptionsandtime-outinterval. public: staticSystem::Text::RegularExpressions::Match^Match(System::String^input,System::String^pattern,System::Text::RegularExpressions::RegexOptionsoptions,TimeSpanmatchTimeout); publicstaticSystem.Text.RegularExpressions.MatchMatch(stringinput,stringpattern,System.Text.RegularExpressions.RegexOptionsoptions,TimeSpanmatchTimeout); staticmemberMatch:string*string*System.Text.RegularExpressions.RegexOptions*TimeSpan->System.Text.RegularExpressions.Match PublicSharedFunctionMatch(inputAsString,patternAsString,optionsAsRegexOptions,matchTimeoutAsTimeSpan)AsMatch Parameters input String Thestringtosearchforamatch. pattern String Theregularexpressionpatterntomatch. options RegexOptions Abitwisecombinationoftheenumerationvaluesthatprovideoptionsformatching. matchTimeout TimeSpan Atime-outinterval,orInfiniteMatchTimeouttoindicatethatthemethodshouldnottimeout. Returns Match Anobjectthatcontainsinformationaboutthematch. Exceptions ArgumentException Aregularexpressionparsingerroroccurred. ArgumentNullException inputorpatternisnull. ArgumentOutOfRangeException optionsisnotavalidbitwisecombinationofRegexOptionsvalues. -or- matchTimeoutisnegative,zero,orgreaterthanapproximately24days. RegexMatchTimeoutException Atime-outoccurred.Formoreinformationabouttime-outs,seetheRemarkssection. Remarks TheMatch(String,String,RegexOptions,TimeSpan)methodreturnsthefirstsubstringthatmatchesaregularexpressionpatterninaninputstring.Forinformationaboutthelanguageelementsusedtobuildaregularexpressionpattern,seeRegularExpressionLanguage-QuickReference. ThestaticMatch(String,String,RegexOptions,TimeSpan)methodisequivalenttoconstructingaRegexobjectwiththeRegex(String,RegexOptions,TimeSpan)constructorandcallingtheinstanceMatch(String)method. Thepatternparameterconsistsofregularexpressionlanguageelementsthatsymbolicallydescribethestringtomatch.Formoreinformationaboutregularexpressions,see.NETRegularExpressionsandRegularExpressionLanguage-QuickReference. YoucandeterminewhethertheregularexpressionpatternhasbeenfoundintheinputstringbycheckingthevalueofthereturnedMatchobject'sSuccessproperty.Ifamatchisfound,thereturnedMatchobject'sValuepropertycontainsthesubstringfrominputthatmatchestheregularexpressionpattern.Ifnomatchisfound,itsvalueisString.Empty. Thismethodreturnsthefirstsubstringfoundininputthatmatchestheregularexpressionpattern.YoucanretrievesubsequentmatchesbyrepeatedlycallingthereturnedMatchobject'sNextMatchmethod.YoucanalsoretrieveallmatchesinasinglemethodcallbycallingtheRegex.Matches(String,String,RegexOptions)method. ThematchTimeoutparameterspecifieshowlongapatternmatchingmethodshouldtrytofindamatchbeforeittimesout.Settingatime-outintervalpreventsregularexpressionsthatrelyonexcessivebacktrackingfromappearingtostoprespondingwhentheyprocessinputthatcontainsnearmatches.Formoreinformation,seeBestPracticesforRegularExpressionsandBacktracking.Ifnomatchisfoundinthattimeinterval,themethodthrowsaRegexMatchTimeoutExceptionexception.matchTimeoutoverridesanydefaulttime-outvaluedefinedfortheapplicationdomaininwhichthemethodexecutes. NotestoCallers WerecommendthatyousetthematchTimeoutparametertoanappropriatevalue,suchastwoseconds.Ifyoudisabletime-outsbyspecifyingInfiniteMatchTimeout,theregularexpressionengineoffersslightlybetterperformance.However,youshoulddisabletime-outsonlyunderthefollowingconditions: Whentheinputprocessedbyaregularexpressionisderivedfromaknownandtrustedsourceorconsistsofstatictext.Thisexcludestextthathasbeendynamicallyinputbyusers. Whentheregularexpressionpatternhasbeenthoroughlytestedtoensurethatitefficientlyhandlesmatches,non-matches,andnearmatches. Whentheregularexpressionpatterncontainsnolanguageelementsthatareknowntocauseexcessivebacktrackingwhenprocessinganearmatch. Seealso RegularExpressionLanguage-QuickReference Appliesto Match(String) SearchesthespecifiedinputstringforthefirstoccurrenceoftheregularexpressionspecifiedintheRegexconstructor. public: System::Text::RegularExpressions::Match^Match(System::String^input); publicSystem.Text.RegularExpressions.MatchMatch(stringinput); memberthis.Match:string->System.Text.RegularExpressions.Match PublicFunctionMatch(inputAsString)AsMatch Parameters input String Thestringtosearchforamatch. Returns Match Anobjectthatcontainsinformationaboutthematch. Exceptions ArgumentNullException inputisnull. RegexMatchTimeoutException Atime-outoccurred.Formoreinformationabouttime-outs,seetheRemarkssection. Examples Thefollowingexamplefindsregularexpressionpatternmatchesinastring,thenliststhematchedgroups,captures,andcapturepositions. #using usingnamespaceSystem; usingnamespaceSystem::Text::RegularExpressions; voidmain() { String^text="Onecarredcarbluecar"; String^pat="(\\w+)\\s+(car)"; //Compiletheregularexpression. Regex^r=gcnewRegex(pat,RegexOptions::IgnoreCase); //Matchtheregularexpressionpatternagainstatextstring. Match^m=r->Match(text); intmatchCount=0; while(m->Success) { Console::WriteLine("Match{0}",++matchCount); for(inti=1;i<=2;i++) { Group^g=m->Groups[i]; Console::WriteLine("Group{0}='{1}'",i,g); CaptureCollection^cc=g->Captures; for(intj=0;jCount;j++) { Capture^c=cc[j]; System::Console::WriteLine("Capture{0}='{1}',Position={2}",j,c,c->Index); } } m=m->NextMatch(); } } //Thisexampledisplaysthefollowingoutput: //Match1 //Group1='One' //Capture0='One',Position=0 //Group2='car' //Capture0='car',Position=4 //Match2 //Group1='red' //Capture0='red',Position=8 //Group2='car' //Capture0='car',Position=12 //Match3 //Group1='blue' //Capture0='blue',Position=16 //Group2='car' //Capture0='car',Position=21 usingSystem; usingSystem.Text.RegularExpressions; classExample { staticvoidMain() { stringtext="Onecarredcarbluecar"; stringpat=@"(\w+)\s+(car)"; //Instantiatetheregularexpressionobject. Regexr=newRegex(pat,RegexOptions.IgnoreCase); //Matchtheregularexpressionpatternagainstatextstring. Matchm=r.Match(text); intmatchCount=0; while(m.Success) { Console.WriteLine("Match"+(++matchCount)); for(inti=1;i<=2;i++) { Groupg=m.Groups[i]; Console.WriteLine("Group"+i+"='"+g+"'"); CaptureCollectioncc=g.Captures; for(intj=0;jSystem.Text.RegularExpressions.Match PublicFunctionMatch(inputAsString,startatAsInteger)AsMatch Parameters input String Thestringtosearchforamatch. startat Int32 Thezero-basedcharacterpositionatwhichtostartthesearch. Returns Match Anobjectthatcontainsinformationaboutthematch. Exceptions ArgumentNullException inputisnull. ArgumentOutOfRangeException startatislessthanzeroorgreaterthanthelengthofinput. RegexMatchTimeoutException Atime-outoccurred.Formoreinformationabouttime-outs,seetheRemarkssection. Remarks TheMatch(String,Int32)methodreturnsthefirstsubstringthatmatchesaregularexpressionpattern,startingatorafterthestartatcharacterposition,inaninputstring.TheregularexpressionpatternforwhichtheMatch(String,Int32)methodsearchesisdefinedbythecalltooneoftheRegexclassconstructors.Forinformationaboutthelanguageelementsusedtobuildaregularexpressionpattern,seeRegularExpressionLanguage-QuickReference. Thestartatparameter Youcanoptionallyspecifyastartingpositioninthestringbyusingthestartatparameter.Anymatchesstartingbeforestartatinthestringareignored.Ifyoudon'tspecifyastartingposition,thesearchbeginsatthedefaultposition,whichistheleftendofinputinaleft-to-rightsearch,andtherightendofinputinaright-to-leftsearch.Despitestartingatstartat,theindexofanyreturnedmatchisrelativetothestartofthestring. Althoughtheregularexpressionenginedoesn'treturnanymatchstartingbeforestartat,itdoesn'tignorethestringbeforestartat.Thismeansthatassertionssuchasanchorsorlookbehindassertionsstillapplytotheinputasawhole.Forexample,thefollowingcodeincludesapatternwithalookbehindassertionthat'ssatisfiedeventhoughitoccursbeforethestartatindexof5intheinputstring. usingSystem; usingSystem.Text.RegularExpressions; namespaceExamples { publicclassExample3 { publicstaticvoidMain() { stringinput="Zipcode:98052"; varregex=newRegex(@"(?<=Zipcode:)\d{5}"); Matchmatch=regex.Match(input,5); if(match.Success) Console.WriteLine("Matchfound:{0}",match.Value); } } } //Thiscodeprintsthefollowingoutput: //Matchfound:98052 Tip Ifapatternstartswiththe^anchorbutstartatisgreaterthan0,nomatcheswilleverbefoundinasingle-linesearchsincetheyareconstrainedby^tostartatindex0. The\Ganchorissatisfiedatstartat.Becauseofthis,ifyouwanttorestrictamatchsothatitbeginsexactlyataparticularcharacterpositioninthestring,anchortheregularexpressionwitha\Gontheleftforaleft-to-rightpattern.Thisrestrictsthematchsoitmuststartexactlyatstartat(or,whenmultiplematchesaredesired,sothematchesarecontiguous). Right-to-leftsearches Aright-to-leftsearch,thatis,whentheregularexpressionpatternisconstructedwiththeRegexOptions.RightToLeftoption,behavesinthefollowingways: Thescanmovesintheoppositedirectionandthepatternismatchedfromback(right)tofront(left). Thedefaultstartingpositionistherightendoftheinputstring. Ifstartatisspecified,theright-to-leftscanbeginsatthecharacteratstartat-1(notstartat). Whenthe\Ganchorisspecifiedattherightendofapattern,itrestrictsthe(first)matchtoendexactlyatstartat-1. Formoreinformationaboutright-to-leftsearches,seeRight-to-leftmode. Determinewhetheramatchisfound YoucandeterminewhethertheregularexpressionpatternhasbeenfoundintheinputstringbycheckingthevalueofthereturnedMatchobject'sSuccessproperty.Ifamatchisfound,thereturnedMatchobject'sValuepropertycontainsthesubstringfrominputthatmatchestheregularexpressionpattern.Ifnomatchisfound,itsvalueisString.Empty. Firstormultiplematches Thismethodreturnsthefirstsubstringfoundatorafterthestartatcharacterpositionininputthatmatchestheregularexpressionpattern.YoucanretrievesubsequentmatchesbyrepeatedlycallingthereturnedMatchobject'sMatch.NextMatchmethod.YoucanalsoretrieveallmatchesinasinglemethodcallbycallingtheRegex.Matches(String,Int32)method. Time-outexceptions TheRegexMatchTimeoutExceptionexceptionisthrowniftheexecutiontimeofthematchingoperationexceedsthetime-outintervalspecifiedbytheRegex.Regex(String,RegexOptions,TimeSpan)constructor.Ifyoudonotsetatime-outintervalwhenyoucalltheconstructor,theexceptionisthrowniftheoperationexceedsanytime-outvalueestablishedfortheapplicationdomaininwhichtheRegexobjectiscreated.Ifnotime-outisdefinedintheRegexconstructorcallorintheapplicationdomain'sproperties,orifthetime-outvalueisRegex.InfiniteMatchTimeout,noexceptionisthrown. Seealso NextMatch() RegularExpressionLanguage-QuickReference Appliesto Match(String,String) Searchesthespecifiedinputstringforthefirstoccurrenceofthespecifiedregularexpression. public: staticSystem::Text::RegularExpressions::Match^Match(System::String^input,System::String^pattern); publicstaticSystem.Text.RegularExpressions.MatchMatch(stringinput,stringpattern); staticmemberMatch:string*string->System.Text.RegularExpressions.Match PublicSharedFunctionMatch(inputAsString,patternAsString)AsMatch Parameters input String Thestringtosearchforamatch. pattern String Theregularexpressionpatterntomatch. Returns Match Anobjectthatcontainsinformationaboutthematch. Exceptions ArgumentException Aregularexpressionparsingerroroccurred. ArgumentNullException inputorpatternisnull. RegexMatchTimeoutException Atime-outoccurred.Formoreinformationabouttime-outs,seetheRemarkssection. Examples ThefollowingexamplecallstheMatch(String,String)methodtofindthefirstwordthatcontainsatleastonezcharacter,andthencallstheMatch.NextMatchmethodtofindanyadditionalmatches. usingSystem; usingSystem.Text.RegularExpressions; namespaceExamples { publicclassExample { publicstaticvoidMain() { stringinput="ablazebeaglechoraldozenelementaryfanatic"+ "glazehungerineptjazzkitchenlemonminus"+ "nightopticalpizzaquizrestorationstamina"+ "trainunrestverticalwhizxrayyellowzealous"; stringpattern=@"\b\w*z+\w*\b"; Matchm=Regex.Match(input,pattern); while(m.Success) { Console.WriteLine("'{0}'foundatposition{1}",m.Value,m.Index); m=m.NextMatch(); } } } } //Theexampledisplaysthefollowingoutput: //'ablaze'foundatposition0 //'dozen'foundatposition21 //'glaze'foundatposition46 //'jazz'foundatposition65 //'pizza'foundatposition104 //'quiz'foundatposition110 //'whiz'foundatposition157 //'zealous'foundatposition174 ImportsSystem.Text.RegularExpressions ModuleExample PublicSubMain() DiminputAsString="ablazebeaglechoraldozenelementaryfanatic"+ "glazehungerineptjazzkitchenlemonminus"+ "nightopticalpizzaquizrestorationstamina"+ "trainunrestverticalwhizxrayyellowzealous" DimpatternAsString="\b\w*z+\w*\b" DimmAsMatch=Regex.Match(input,pattern) DoWhilem.Success Console.WriteLine("'{0}'foundatposition{1}",m.Value,m.Index) m=m.NextMatch() Loop EndSub EndModule 'Theexampledisplaysthefollowingoutput: 'ablaze'foundatposition0 'dozen'foundatposition21 'glaze'foundatposition46 'jazz'foundatposition65 'pizza'foundatposition104 'quiz'foundatposition110 'whiz'foundatposition157 'zealous'foundatposition174 Theregularexpressionpattern\b\w*z+\w*\bisinterpretedasshowninthefollowingtable. Pattern Description \b Beginthematchatawordboundary. \w* Matchzero,one,ormorewordcharacters. z+ Matchoneormoreoccurrencesofthezcharacter. \w* Matchzero,one,ormorewordcharacters. \b Endthematchatawordboundary. Remarks TheMatch(String,String)methodreturnsthefirstsubstringthatmatchesaregularexpressionpatterninaninputstring.Forinformationaboutthelanguageelementsusedtobuildaregularexpressionpattern,seeRegularExpressionLanguage-QuickReference. ThestaticMatch(String,String)methodisequivalenttoconstructingaRegexobjectwiththespecifiedregularexpressionpatternandcallingtheinstanceMatch(String)method.Inthiscase,theregularexpressionenginecachestheregularexpressionpattern. Thepatternparameterconsistsofregularexpressionlanguageelementsthatsymbolicallydescribethestringtomatch.Formoreinformationaboutregularexpressions,see.NETRegularExpressionsandRegularExpressionLanguage-QuickReference. YoucandeterminewhethertheregularexpressionpatternhasbeenfoundintheinputstringbycheckingthevalueofthereturnedMatchobject'sSuccessproperty.Ifamatchisfound,thereturnedMatchobject'sValuepropertycontainsthesubstringfrominputthatmatchestheregularexpressionpattern.Ifnomatchisfound,itsvalueisString.Empty. Thismethodreturnsthefirstsubstringininputthatmatchestheregularexpressionpattern.YoucanretrievesubsequentmatchesbyrepeatedlycallingthereturnedMatchobject'sMatch.NextMatchmethod.YoucanalsoretrieveallmatchesinasinglemethodcallbycallingtheRegex.Matches(String,String)method. TheRegexMatchTimeoutExceptionexceptionisthrowniftheexecutiontimeofthematchingoperationexceedsthetime-outintervalspecifiedfortheapplicationdomaininwhichthemethodiscalled.Ifnotime-outisdefinedintheapplicationdomain'sproperties,orifthetime-outvalueisRegex.InfiniteMatchTimeout,noexceptionisthrown. NotestoCallers Thismethodtimesoutafteranintervalthatisequaltothedefaulttime-outvalueoftheapplicationdomaininwhichitiscalled.Ifatime-outvaluehasnotbeendefinedfortheapplicationdomain,thevalueInfiniteMatchTimeout,whichpreventsthemethodfromtimingout,isused.TherecommendedstaticmethodforretrievingapatternmatchisMatch(String,String),whichletsyousetthetime-outinterval. Seealso NextMatch() RegularExpressionLanguage-QuickReference Appliesto Match(String,Int32,Int32) Searchestheinputstringforthefirstoccurrenceofaregularexpression,beginningatthespecifiedstartingpositionandsearchingonlythespecifiednumberofcharacters. public: System::Text::RegularExpressions::Match^Match(System::String^input,intbeginning,intlength); publicSystem.Text.RegularExpressions.MatchMatch(stringinput,intbeginning,intlength); memberthis.Match:string*int*int->System.Text.RegularExpressions.Match PublicFunctionMatch(inputAsString,beginningAsInteger,lengthAsInteger)AsMatch Parameters input String Thestringtosearchforamatch. beginning Int32 Thezero-basedcharacterpositionintheinputstringthatdefinestheleftmostpositiontobesearched. length Int32 Thenumberofcharactersinthesubstringtoincludeinthesearch. Returns Match Anobjectthatcontainsinformationaboutthematch. Exceptions ArgumentNullException inputisnull. ArgumentOutOfRangeException beginningislessthanzeroorgreaterthanthelengthofinput. -or- lengthislessthanzeroorgreaterthanthelengthofinput. -or- beginning+length-1identifiesapositionthatisoutsidetherangeofinput. RegexMatchTimeoutException Atime-outoccurred.Formoreinformationabouttime-outs,seetheRemarkssection. Remarks TheMatch(String,Int32,Int32)methodreturnsthefirstsubstringthatmatchesaregularexpressionpatterninaportionofaninputstring.Forinformationaboutthelanguageelementsusedtobuildaregularexpressionpattern,seeRegularExpressionLanguage-QuickReference. TheregularexpressionpatternforwhichtheMatch(String,Int32,Int32)methodsearchesisdefinedbythecalltooneoftheRegexclassconstructors.Formoreinformationabouttheelementsthatcanformaregularexpressionpattern,seeRegularExpressionLanguage-QuickReference. TheMatch(String,Int32,Int32)methodsearchestheportionofinputdefinedbythebeginningandlengthparametersfortheregularexpressionpattern.beginningalwaysdefinestheindexoftheleftmostcharactertoincludeinthesearch,andlengthdefinesthemaximumnumberofcharacterstosearch.Together,theydefinetherangeofthesearch.Thebehaviorisexactlyasiftheinputwaseffectivelyinput.Substring(beginning,length),exceptthattheindexofanymatchiscountedrelativetothestartofinput.Thismeansthatanyanchorsorzero-widthassertionsatthestartorendofthepatternbehaveasifthereisnoinputoutsideofthisrange.Forexampletheanchors^,\G,and\Awillbesatisfiedatbeginningand$and\zwillbesatisfiedatbeginning+length-1. Ifthesearchproceedsfromlefttoright(thedefault),theregularexpressionenginesearchesfromthecharacteratindexbeginningtothecharacteratindexbeginning+length-1.IftheregularexpressionenginewasinstantiatedbyusingtheRegexOptions.RightToLeftoptionsothatthesearchproceedsfromrighttoleft,theregularexpressionenginesearchesfromthecharacteratindexbeginning+length-1tothecharacteratindexbeginning. Thismethodreturnsthefirstmatchthatitfindswithinthisrange.YoucanretrievesubsequentmatchesbyrepeatedlycallingthereturnedMatchobject'sMatch.NextMatchmethod. YoucandeterminewhethertheregularexpressionpatternhasbeenfoundintheinputstringbycheckingthevalueofthereturnedMatchobject'sSuccessproperty.Ifamatchisfound,thereturnedMatchobject'sValuepropertycontainsthesubstringfrominputthatmatchestheregularexpressionpattern.Ifnomatchisfound,itsvalueisString.Empty. TheRegexMatchTimeoutExceptionexceptionisthrowniftheexecutiontimeofthematchingoperationexceedsthetime-outintervalspecifiedbytheRegex.Regex(String,RegexOptions,TimeSpan)constructor.Ifyoudonotsetatime-outvaluewhenyoucalltheconstructor,theexceptionisthrowniftheoperationexceedsanytime-outvalueestablishedfortheapplicationdomaininwhichtheRegexobjectiscreated.Ifnotime-outisdefinedintheRegexconstructorcallorintheapplicationdomain'sproperties,orifthetime-outvalueisRegex.InfiniteMatchTimeout,noexceptionisthrown. Seealso NextMatch() RegularExpressionLanguage-QuickReference Appliesto Match(String,String,RegexOptions) Searchestheinputstringforthefirstoccurrenceofthespecifiedregularexpression,usingthespecifiedmatchingoptions. public: staticSystem::Text::RegularExpressions::Match^Match(System::String^input,System::String^pattern,System::Text::RegularExpressions::RegexOptionsoptions); publicstaticSystem.Text.RegularExpressions.MatchMatch(stringinput,stringpattern,System.Text.RegularExpressions.RegexOptionsoptions); staticmemberMatch:string*string*System.Text.RegularExpressions.RegexOptions->System.Text.RegularExpressions.Match PublicSharedFunctionMatch(inputAsString,patternAsString,optionsAsRegexOptions)AsMatch Parameters input String Thestringtosearchforamatch. pattern String Theregularexpressionpatterntomatch. options RegexOptions Abitwisecombinationoftheenumerationvaluesthatprovideoptionsformatching. Returns Match Anobjectthatcontainsinformationaboutthematch. Exceptions ArgumentException Aregularexpressionparsingerroroccurred. ArgumentNullException inputorpatternisnull. ArgumentOutOfRangeException optionsisnotavalidbitwisecombinationofRegexOptionsvalues. RegexMatchTimeoutException Atime-outoccurred.Formoreinformationabouttime-outs,seetheRemarkssection. Examples Thefollowingexampledefinesaregularexpressionthatmatcheswordsbeginningwiththeletter"a".ItusestheRegexOptions.IgnoreCaseoptiontoensurethattheregularexpressionlocateswordsbeginningwithbothanuppercase"a"andalowercase"a". usingSystem; usingSystem.Text.RegularExpressions; namespaceExamples { publicclassExample2 { publicstaticvoidMain() { stringpattern=@"\ba\w*\b"; stringinput="Anextraordinarydaydawnswitheachnewday."; Matchm=Regex.Match(input,pattern,RegexOptions.IgnoreCase); if(m.Success) Console.WriteLine("Found'{0}'atposition{1}.",m.Value,m.Index); } } } //Theexampledisplaysthefollowingoutput: //Found'An'atposition0. ImportsSystem.Text.RegularExpressions ModuleExample PublicSubMain() DimpatternAsString="\ba\w*\b" DiminputAsString="Anextraordinarydaydawnswitheachnewday." DimmAsMatch=Regex.Match(input,pattern,RegexOptions.IgnoreCase) Ifm.SuccessThen Console.WriteLine("Found'{0}'atposition{1}.",m.Value,m.Index) EndIf EndSub EndModule 'Theexampledisplaysthefollowingoutput: 'Found'An'atposition0. Theregularexpressionpattern\ba\w*\bisinterpretedasshowninthefollowingtable. Pattern Description \b Beginthematchatawordboundary. a Matchthecharacter"a". \w* Matchzero,one,ormorewordcharacters. \b Endthematchatawordboundary. Remarks TheMatch(String,String,RegexOptions)methodreturnsthefirstsubstringthatmatchesaregularexpressionpatterninaninputstring.Forinformationaboutthelanguageelementsusedtobuildaregularexpressionpattern,seeRegularExpressionLanguage-QuickReference. ThestaticMatch(String,String,RegexOptions)methodisequivalenttoconstructingaRegexobjectwiththeRegex(String,RegexOptions)constructorandcallingtheinstanceMatch(String)method. Thepatternparameterconsistsofregularexpressionlanguageelementsthatsymbolicallydescribethestringtomatch.Formoreinformationaboutregularexpressions,see.NETRegularExpressionsandRegularExpressionLanguage-QuickReference. YoucandeterminewhethertheregularexpressionpatternhasbeenfoundintheinputstringbycheckingthevalueofthereturnedMatchobject'sSuccessproperty.Ifamatchisfound,thereturnedMatchobject'sValuepropertycontainsthesubstringfrominputthatmatchestheregularexpressionpattern.Ifnomatchisfound,itsvalueisString.Empty. Thismethodreturnsthefirstsubstringfoundininputthatmatchestheregularexpressionpattern.YoucanretrievesubsequentmatchesbyrepeatedlycallingthereturnedMatchobject'sNextMatchmethod.YoucanalsoretrieveallmatchesinasinglemethodcallbycallingtheRegex.Matches(String,String,RegexOptions)method. TheRegexMatchTimeoutExceptionexceptionisthrowniftheexecutiontimeofthematchingoperationexceedsthetime-outintervalspecifiedfortheapplicationdomaininwhichthemethodiscalled.Ifnotime-outisdefinedintheapplicationdomain'sproperties,orifthetime-outvalueisRegex.InfiniteMatchTimeout,noexceptionisthrown. NotestoCallers Thismethodtimesoutafteranintervalthatisequaltothedefaulttime-outvalueoftheapplicationdomaininwhichitiscalled.Ifatime-outvaluehasnotbeendefinedfortheapplicationdomain,thevalueInfiniteMatchTimeout,whichpreventsthemethodfromtimingout,isused.TherecommendedstaticmethodforretrievingapatternmatchisMatch(String,String),whichletsyousetthetime-outinterval. Seealso NextMatch() RegularExpressionLanguage-QuickReference Appliesto Inthisarticle



請為這篇文章評分?