regex - Why doesn't [01-12] range work as expected?

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

Your goal is evidently to specify a number range: any number between 01 and 12 written with two digits. In this specific case, you can match it ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Whydoesn't[01-12]rangeworkasexpected? AskQuestion Asked 12yearsago Modified 1year,4monthsago Viewed 187ktimes 119 27 I'mtryingtousetherangepattern[01-12]inregextomatchtwodigitmm,butthisdoesn'tworkasexpected. regex Share Improvethisquestion Follow editedJul8,2015at5:36 Jerry 68.8k1212goldbadges9797silverbadges139139bronzebadges askedJun30,2010at10:14 DEACTIVATIONPRESCRIPTION.NETDEACTIVATIONPRESCRIPTION.NET 1,56533goldbadges1212silverbadges1010bronzebadges 4 10 You'rematchingcharacters,notcharactersequences.Basically,you'rematchingagainst0,1to1,and2(ie.0,1and2).Considerthis:[a-z0-9],thismatchesallthelowercaseletter,andallthedigits,butonlyasasinglecharacter. – LasseV.Karlsen Jun30,2010at10:18 fwiwIcreatedajavascripttoolthatcreatesahighlyoptimizedregexfromtwoinputs(min/max)github.com/jonschlinkert/to-regex-range – jonschlinkert Apr21,2017at10:18 0[1-9]|1[0-2]->0|1|2->[]sinaregexdenoteacharacterclass.Ifnorangesarespecified,itimplicitlyorseverycharacter. – BadriGs Aug4,2017at5:08 Doyouneedtomatchitwithpureregex?Ifnot,youcan:1.)justsimplyusethe\d+pattern,2.)convertthematchedstringstonumbersinyourcode.andthen,3.)checkthenumberrangelikeif(num>=0&&num<=12){/*dosomething*/}.It'ssomuchfasterandflexible. – acegs Apr26,2018at5:47 Addacomment  |  7Answers 7 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 247 Youseemtohavemisunderstoodhowcharacterclassesdefinitionworksinregex. Tomatchanyofthestrings01,02,03,04,05,06,07,08,09,10,11,or12,somethinglikethisworks: 0[1-9]|1[0-2] References regular-expressions.info/CharacterClasses NumericRanges(havemanyexamplesonmatchingstringsinterpretedasnumericranges) Explanation Acharacterclass,byitself,attemptstomatchoneandexactlyonecharacterfromtheinputstring.[01-12]actuallydefines[012],acharacterclassthatmatchesonecharacterfromtheinputagainstanyofthe3characters0,1,or2. The-rangedefinitiongoesfrom1to1,whichincludesjust1.Ontheotherhand,somethinglike[1-9]includes1,2,3,4,5,6,7,8,9. Beginnersoftenmakethemistakesofdefiningthingslike[this|that].Thisdoesn't"work".Thischaracterdefinitiondefines[this|a],i.e.itmatchesonecharacterfromtheinputagainstanyof6charactersint,h,i,s,|ora.Morethanlikely(this|that)iswhatisintended. References regular-expressions.info/BracketsforGroupingandAlternationwiththeverticalbar Howrangesaredefined Soit'sobviousnowthatapatternlikebetween[24-48]hoursdoesn't"work".Thecharacterclassinthiscaseisequivalentto[248]. Thatis,-inacharacterclassdefinitiondoesn'tdefinenumericrangeinthepattern.Regexenginesdoesn'treally"understand"numbersinthepattern,withtheexceptionoffiniterepetitionsyntax(e.g.a{3,5}matchesbetween3and5a). RangedefinitioninsteadusesASCII/Unicodeencodingofthecharacterstodefineranges.Thecharacter0isencodedinASCIIasdecimal48;9is57.Thus,thecharacterdefinition[0-9]includesallcharacterwhosevaluesarebetweendecimal48and57intheencoding.Rathersensibly,bydesignthesearethecharacters0,1,...,9. Seealso Wikipedia/ASCII Anotherexample:AtoZ Let'stakealookatanothercommoncharacterclassdefinition[a-zA-Z] InASCII: A=65,Z=90 a=97,z=122 Thismeansthat: [a-zA-Z]and[A-Za-z]areequivalent Inmostflavors,[a-Z]islikelytobeanillegalcharacterrange becausea(97)is"greaterthan"thanZ(90) [A-z]islegal,butalsoincludesthesesixcharacters: [(91),\(92),](93),^(94),_(95),`(96) Relatedquestions istheregex[a-Z]validandifyesthenisitthesameas[a-zA-Z] Share Improvethisanswer Follow editedJun24,2019at11:38 FuXiangShu 10088bronzebadges answeredJun30,2010at10:15 polygenelubricantspolygenelubricants 365k124124goldbadges555555silverbadges619619bronzebadges 5 Forme,Iwaslookingformonthswithoutprefixingwith0ifsingledigit.AndIusedthis([1-9]|(1[0-2]))anditworks. – bunjeeb Feb18,2017at0:39 4 Importanttonote:Ifyoufindthispagewantingasolutionforyournumberrangethatonlyhassingledigitsbeforegettingtothetens,0[1-9]|1[0-2]won'twork.Changingittothelogicalnextstep[1-9]|1[0-2]doesn'tworkeitherforunderstandablereasons(Itmatchesthe1onlyin10,11,and12).Hadtouse\b(?:[0-9]|1[0-1])\btopreventthat.\b'smakessureregexmatchesword(orinthiscasenumber)boundaries(^&$didn't);bracketsmaketheor(|)considertheothersideofit;andfinally?:istonotcreateasubmatchwiththeuseofthebrackets. – user66001 Apr13,2017at19:05 @polygenelubricants:"1,2,3,4,5,6,7,8,9,10,17,18".match(/^(([1-9]|1[0-7])\,?)+$/g)CanyoupleasetellmewhyisthisJSregexmatchesabove17? – edam Jan24,2018at13:39 @edam-polygenelubricantscould,andsocouldI,butthenwe'dbeansweringaquesti…wait…isthisaquestionyouareaskinginacomment?Therearerulezonthissite;)AskaQuestionifyouhaveanewquestion.Commentsareonlyforcritiquingandaskingforclarification,andforrespondingtothose. – robinCTS Mar9,2018at4:42 1 @edamOh,Isee.Youdidre-askitasaquestionanhourlater.That'sgreat!However,itwouldprobablybeagoodideatodeleteyourcommenthere. – robinCTS Mar13,2018at11:11 Addacomment  |  28 Acharacterclassinregularexpressions,denotedbythe[...]syntax,specifiestherulestomatchasinglecharacterintheinput.Assuch,everythingyouwritebetweenthebracketsspecifyhowtomatchasinglecharacter. Yourpattern,[01-12]isthusbrokendownasfollows: 0-matchthesingledigit0 or,1-1,matchasingledigitintherangeof1through1 or,2,matchasingledigit2 Sobasicallyallyou'rematchingis0,1or2. Inordertodothematchingyouwant,matchingtwodigits,rangingfrom01-12asnumbers,youneedtothinkabouthowtheywilllookastext. Youhave: 01-09(ie.firstdigitis0,seconddigitis1-9) 10-12(ie.firstdigitis1,seconddigitis0-2) Youwillthenhavetowritearegularexpressionforthat,whichcanlooklikethis: +--a0followedby1-9 | |+--a1followedby0-2 || 0[1-9]|1[0-2] ^ | +--verticalbar,thisroughlymeans"OR"inthiscontext Notethattryingtocombinetheminordertogetashorterexpressionwillfail,bygivingfalsepositivematchesforinvalidinput. Forinstance,thepattern[0-1][0-9]wouldbasicallymatchthenumbers00-19,whichisabitmorethanwhatyouwant. Itriedfindingadefinitesourceformoreinformationaboutcharacterclasses,butfornowallIcangiveyouisthisGoogleQueryforRegexCharacterClasses.Hopefullyyou'llbeabletofindsomemoreinformationtheretohelpyou. Share Improvethisanswer Follow answeredJun30,2010at10:21 LasseV.KarlsenLasseV.Karlsen 368k9696goldbadges613613silverbadges799799bronzebadges Addacomment  |  10 Thisalsoworks: ^([1-9]|[0-1][0-2])$ [1-9]matchessingledigitsbetween1and9 [0-1][0-2]matchesdoubledigitsbetween10and12 Therearesomegoodexampleshere Share Improvethisanswer Follow answeredJun30,2010at10:27 codingbadgercodingbadger 40.8k1313goldbadges9393silverbadges109109bronzebadges 2 2 Tobeexact,[0-1][0-2]alsomatches00.Thatsaid,+1forthelink(whichI'veusedinmyanswer). – polygenelubricants Jun30,2010at11:05 2 [0-1][0-2]mustbecarefullyinterpreted,asitallowsstringslike00,01,and02,butitdoesn'tadmit03upto09,admittingfinally10,11and12.Arightregexforthatis[1-9]|1[0-2],oreven0*([1-9]|1[0-2])(thislastallowinganynumberofleadingzeros). – LuisColorado Sep23,2015at20:50 Addacomment  |  1 The[]sinaregexdenoteacharacterclass.Ifnorangesarespecified,itimplicitlyorseverycharacterwithinittogether.Thus,[abcde]isthesameas(a|b|c|d|e),exceptthatitdoesn'tcaptureanything;itwillmatchanyoneofa,b,c,d,ore.Allarangeindicatesisasetofcharacters;[ac-eg]says"matchanyoneof:a;anycharacterbetweencande;org".Thus,yourmatchsays"matchanyoneof:0;anycharacterbetween1and1(i.e.,just1);or2. Yourgoalisevidentlytospecifyanumberrange:anynumberbetween01and12writtenwithtwodigits.Inthisspecificcase,youcanmatchitwith0[1-9]|1[0-2]:eithera0followedbyanydigitbetween1and9,ora1followedbyanydigitbetween0and2.Ingeneral,youcantransformanynumberrangeintoavalidregexinasimilarmanner.Theremaybeabetteroptionthanregularexpressions,however,oranexistingfunctionormodulewhichcanconstructtheregexforyou.Itdependsonyourlanguage. Share Improvethisanswer Follow answeredJun30,2010at10:20 AntalSpector-ZabuskyAntalSpector-Zabusky 35.6k66goldbadges7777silverbadges137137bronzebadges Addacomment  |  1 Usethis: 0?[1-9]|1[012] 07:valid 7:valid 0:notmatch 00:notmatch 13:notmatch 21:notmatch Totestapatternas07/2018usethis: /^(0?[1-9]|1[012])\/([2-9][0-9]{3})$/ (Daterangebetween01/2000to12/9999) Share Improvethisanswer Follow editedJul7,2018at7:10 answeredJan23,2018at7:24 EoliaEolia 20722silverbadges44bronzebadges 1 I'vebeentryingtofigureouthowtodothisbuttogetthethirdconditionofonlya0topass. – Matt Jul5,2018at19:59 Addacomment  |  0 Aspolygenelubricantssaysyourswouldlookfor0|1-1|2ratherthanwhatyouwishfor,duetothefactthatcharacterclasses(thingsin[])matchcharactersratherthanstrings. Share Improvethisanswer Follow answeredJun30,2010at10:17 fbstjfbstj 1,67411goldbadge1616silverbadges2222bronzebadges 1 3 0|1-1|2-thisnotationisverymisleading.Somethinglike0|1|2wouldbemoreaccurate. – polygenelubricants Jun30,2010at10:28 Addacomment  |  0 Mysolutiontokeepmm-yyyyis^0*([1-9]|1[0-2])-(20[2-4][0-9])$ Share Improvethisanswer Follow answeredMar4,2021at13:28 FalconTechFalconTech 4622bronzebadges 2 Probablybetter^(0?[1-9]|1[0-2)-…(onlyasingleoptionalleading0inthenotdoubledigitcase) – eckes Jul2,2021at15:21 True,single(?)isbetterthanunlimited(*). – FalconTech Jul3,2021at16:48 Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedregexoraskyourownquestion. TheOverflowBlog WhyPerlisstillrelevantin2022 Skillsthatpaythebillsforsoftwaredevelopers(Ep.460) FeaturedonMeta Testingnewtrafficmanagementtool Duplicatedvotesarebeingcleanedup Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Linked -5 Whydoesregularexpression'r[1900-2023]+'doesn'treturnsrangeofvaluesbetween1900to2023? 0 Unabletocreateregex 2 Matchsequenceofdigitswithregularexpressions 0 Whywon'tthisregexwork? 1 Regex:Basicpatternfordateformat(dd.mm.yyyy)notworking 0 Pythonregexnotfindinganumberintherangeof1to34asexpected -2 Regularexpressionisnotworkingasexpectedfornumber"4" -3 ValidateastateviaitspincodeinJava -1 HowdoIsimplifythatregex? 0 RegExforvalueRangefrom1,00-365,00with2digitsaftercomma Seemorelinkedquestions Related 1020 Howtovalidatephonenumbersusingregex 4979 Regularexpressiontomatchalinethatdoesn'tcontainaword 1626 HowdoyouaccessthematchedgroupsinaJavaScriptregularexpression? 1751 Howdoyouuseavariableinaregularexpression? 466 Regex:matcheverythingbutaspecificpattern 2005 RegExmatchopentagsexceptXHTMLself-containedtags 732 Regularexpressiontostopatfirstmatch 1202 Negativematchingusinggrep(matchlinesthatdonotcontainfoo) 1002 CheckwhetherastringmatchesaregexinJS 1319 \dlessefficientthan[0-9] HotNetworkQuestions Whydoesbashtreatundefinedsymbolsastrueinanifstatement? BamaKhepa/Tarapith&DifferentTypesofBhakti Isthereanultimatebreak-evenpointwithrocketnozzlelengthorexpansionratioinavacuum? Isitlegalforanairlinetoshow,atthesameexacttime,todifferentpricesforthesameexactflight? WhatkindofadderdoesthedefaultVerilogadditionoperatorimplement? NumberofsignificantdigitsinuncertaintyofAround LookingforaPC2Dplatformergamefromthemid-2000sorearlier Visualizeacontinuousvariableagainstabinaryvariable HowoftendoIhavetokeepdumpingdebrisintoorbitaroundaplanettokeepitsinhabitantsfrombeingabletoleave? Short-termcapitalgainstaxoncryptocurrency ZenerDiodeTransientBehaviour IsthereanypossibilitythatCERN'sLargeHadronColliderrun3canbedevastating? UnusualroutesfromUKtoDenmark TheUnreasonableIneffectivenessofMathematicsinmostsciences DevelopmentofOldNorse2ndand3rdpersonsg.(presentindicative)formsof"tobe" Arethereanyclass-changingprefixesinEnglish? Whatiswrongwithtreatingeverythingasahyperparameter? Children'sbookwith"aring,astone,afingerbone" Addintheblanks Areboysgenerally"lazy"intheirearlyteens? DeterminedvsUniquelyDetermined Is"vehicle"really"транспортнийзасіб"?Dopeoplesaythat? HowcanImakethesenumberscenteraligned? Onehotlegtoneutralof4-prongdryerreading240voltsandotherhotlegtoneutralreading0volts morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?