Example: Matching Numeric Ranges with a Regular Expression

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

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99 ... Quick StartTutorialTools & LanguagesExamplesReferenceBook Reviews ExamplesRegularExpressionsExamplesNumericRangesFloatingPointNumbersEmailAddressesIPAddressesValidDatesNumericDatestoTextCreditCardNumbersMatchingCompleteLinesDeletingDuplicateLinesProgrammingTwoNearWords PitfallsCatastrophicBacktrackingTooManyRepetitionsDenialofServiceMakingEverythingOptionalRepeatedCapturingGroupMixingUnicode&8-bit MoreonThisSiteIntroductionRegularExpressionsQuickStartRegularExpressionsTutorialReplacementStringsTutorialApplicationsandLanguagesRegularExpressionsExamplesRegularExpressionsReferenceReplacementStringsReferenceBookReviewsPrintablePDFAboutThisSiteRSSFeed&BlogMatchingNumericRangeswithaRegularExpressionSinceregularexpressionsdealwithtextratherthanwithnumbers,matchinganumberinagivenrangetakesalittleextracare.Youcan’tjustwrite[0-255]tomatchanumberbetween0and255.Thoughavalidregex,itmatchessomethingentirelydifferent.[0-255]isacharacterclasswiththreeelements:thecharacterrange0-2,thecharacter5andthecharacter5(again).Thischaracterclassmatchesasingledigit0,1,2or5,justlike[0125].Sinceregularexpressionsworkwithtext,aregularexpressionenginetreats0asasinglecharacter,and255asthreecharacters.Tomatchallcharactersfrom0to255,we’llneedaregexthatmatchesbetweenoneandthreecharacters.Theregex[0-9]matchessingle-digitnumbers0to9.[1-9][0-9]matchesdouble-digitnumbers10to99.That’stheeasypart.Matchingthethree-digitnumbersisalittlemorecomplicated,sinceweneedtoexcludenumbers256through999.1[0-9][0-9]takescareof100to199.2[0-4][0-9]matches200through249.Finally,25[0-5]adds250till255.Asyoucansee,youneedtosplitupthenumericrangeinrangeswiththesamenumberofdigits,andeachofthoserangesthatallowthesamevariationforeachdigit.Inthe3-digitrangeinourexample,numbersstartingwith1allowall10digitsforthefollowingtwodigits,whilenumbersstartingwith2restrictthedigitsthatareallowedtofollow.Puttingthisalltogetherusingalternationweget:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5].Thismatchesthenumberswewant,withonecaveat:regularexpressionsearchesusuallyallowpartialmatches,soourregexwouldmatch123in12345.Therearetwosolutionstothis.SearchingforNumericRangesIfyou’researchingforthesenumbersinalargerdocumentorinputstring,usewordboundariestorequireanon-wordcharacter(ornocharacteratall)toprecedeandtofollowanyvalidmatch.Theregexthenbecomes\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b.Sincethealternationoperatorhasthelowestprecedenceofall,theparenthesesarerequiredtogroupthealternativestogether.Thiswaytheregexenginewilltrytomatchthefirstwordboundary,thentryallthealternatives,andthentrytomatchthesecondwordboundaryafterthenumbersitmatched.Regularexpressionenginesconsiderallalphanumericcharacters,aswellastheunderscore,aswordcharacters.ValidatingNumericRangesIfyou’reusingtheregularexpressiontovalidateinput,you’llprobablywanttocheckthattheentireinputconsistsofavalidnumber.Todothis,replacethewordboundarieswithanchorstomatchthestartandendofthestring:^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$.Hereareafewmorecommonrangesthatyoumaywanttomatch:000..255:^([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$0or000..255:^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$0or000..127:^(0?[0-9]?[0-9]|1[01][0-9]|12[0-7])$0..999:^([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$000..999:^[0-9]{3}$0or000..999:^[0-9]{1,3}$1..999:^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$001..999:^(00[1-9]|0[1-9][0-9]|[1-9][0-9][0-9])$1or001..999:^(0{0,2}[1-9]|0?[1-9][0-9]|[1-9][0-9][0-9])$0or00..59:^[0-5]?[0-9]$0or000..366:^([012]?[0-9]?[0-9]|3[0-5][0-9]|36[0-6])$| Quick Start | Tutorial | Tools & Languages | Examples | Reference | Book Reviews || RegularExpressionsExamples | NumericRanges | FloatingPointNumbers | EmailAddresses | IPAddresses | ValidDates | NumericDatestoText | CreditCardNumbers | MatchingCompleteLines | DeletingDuplicateLines | Programming | TwoNearWords || CatastrophicBacktracking | TooManyRepetitions | DenialofService | MakingEverythingOptional | RepeatedCapturingGroup | MixingUnicode&8-bit |PageURL:https://www.regular-expressions.info/numericranges.htmlPagelastupdated:2September2021Sitelastupdated:19May2022Copyright©2003-2022JanGoyvaerts.Allrightsreserved.



請為這篇文章評分?