116 - Stack Overflow
文章推薦指數: 80 %
The regular expression for this is really simple. Just use a character class. The hyphen is a special character in character classes, ... 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 RegextoMatchSymbols:!$%^&*()_+|~-=`{}[]:";'<>?,./ AskQuestion Asked 10years,7monthsago Modified 14daysago Viewed 404ktimes 116 42 I'mtryingtocreateaRegextestinJavaScriptthatwilltestastringtocontainanyofthesecharacters: !$%^&*()_+|~-=`{}[]:";'<>?,./ MoreInfoIfYou'reInterested:) It'sforaprettycoolpasswordchangeapplicationI'mworkingon.Incaseyou'reinterestedhere'stherestofthecode. Ihaveatablethatlistspasswordrequirementsandasend-userstypesthenewpassword,itwilltestanarrayofRegexesandplaceacheckmarkinthecorrespondingtablerowifit...checksout:)Ijustneedtoaddthisoneinplaceofthe4thiteminthevalidationarray. varvalidate=function(password){ valid=true; varvalidation=[ RegExp(/[a-z]/).test(password),RegExp(/[A-Z]/).test(password),RegExp(/\d/).test(password), RegExp(/\W|_/).test(password),!RegExp(/\s/).test(password),!RegExp("12345678").test(password), !RegExp($('#txtUsername').val()).test(password),!RegExp("cisco").test(password), !RegExp(/([a-z]|[0-9])\1\1\1/).test(password),(password.length>7) ] $.each(validation,function(i){ if(this) $('.formtabletr').eq(i+1).attr('class','check'); else{ $('.formtabletr').eq(i+1).attr('class',''); valid=false } }); return(valid); } Yes,there'salsocorrespondingserver-sidevalidation! javascriptjqueryregex Share Improvethisquestion Follow editedSep17,2016at20:58 pixelbobby askedDec2,2011at16:38 pixelbobbypixelbobby 4,29944goldbadges2727silverbadges4545bronzebadges 4 12 It'squitefunnythattheanswertoyourquestionliesinthetitlewiththeexceptionofescapingspecialcharactersandenclosingforwardslashes. – sciritai Dec2,2011at16:46 1 Whynotuse.addClass("check")and.removeClass("check")?Andseeingif(someBoolean==true)incodealwaysmakesmecringe.Justdoif(someBoolean).Or,betteryet,justdo$(".formtabletr").eq(i+1).toggleClass("check",!!this);valid=valid&&!!this;. – gilly3 Dec2,2011at16:46 [email protected]'vedefusedthoseshort-handmethodsinthepast. – pixelbobby Dec2,2011at17:59 @gilly3,itappearstoworkgreatinFFbut!IE8.lovethisshort-hand.I'mtryingtofigureoutwhatIE8isdoingdifferently. – pixelbobby Dec2,2011at18:14 Addacomment | 8Answers 8 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 199 Theregularexpressionforthisisreallysimple.Justuseacharacterclass.Thehyphenisaspecialcharacterincharacterclasses,soitneedstobefirst: /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/ Youalsoneedtoescapetheotherregularexpressionmetacharacters. Edit: Thehyphenisspecialbecauseitcanbeusedtorepresentarangeofcharacters.Thissamecharacterclasscanbesimplifiedwithrangestothis: /[$-/:-?{-~!"^_`\[\]]/ Therearethreeranges.'$'to'/',':'to'?',and'{'to'~'.thelaststringofcharacterscan'tberepresentedmoresimplywitharange:!"^_`[]. UseanACSIItabletofindrangesforcharacterclasses. Share Improvethisanswer Follow editedDec2,2011at17:12 answeredDec2,2011at16:42 JeffHillmanJeffHillman 7,40033goldbadges3232silverbadges3434bronzebadges 10 Whyisnotmentionedquantifiers\Qand\Eforescapingthesequenceofcharacters? – SerG May27,2014at8:29 BeforefindingthissolutionIwasgoingdownthecharacterclassexclusionroute:matcheverythingBUTalpha,digits,whitespace,etc. – PeteAlvin Apr29,2015at13:00 1 Isitcommonknowledgethathyphenshavetocomefirst?I'vereaddozensofSOanswersandregexcheatsheetsthisisthefirstI'veheardofit.Youranswersavedmealotofdrama.Thanks! – CF_HoneyBadger Jun29,2016at14:57 2 @SerG\Qand\Edon'tworkintheJSRegExpengine:(/^\Q.\E$/.test('Q+E');//true – PaulS. Sep17,2016at21:04 1 @q4w56backslashisn'tinthesetofcharactersspecifiedintheoriginalquestion,sonotmatchingbackslashiscorrect.:) – JeffHillman Jun2,2017at23:32 | Show5morecomments 14 Themostsimpleandshortestwaytoaccomplishthis: /[^\p{L}\d\s@#]/u Explanation [^...]Matchasinglecharacternotpresentinthelistbelow \p{L}=>matchesanykindofletterfromanylanguage \d=>matchesadigitzerothroughnine \s=>matchesanykindofinvisiblecharacter @#=>@and#characters Don'tforgettopasstheu(unicode)flag. Share Improvethisanswer Follow editedSep3,2020at12:31 answeredJan18,2019at15:21 AmirZprAmirZpr 24322silverbadges99bronzebadges 6 wouldn'tyouneeda^toindicatenot? – Webber Jan28,2019at16:57 1 @WebberNo.They'reincapitalandthismakesthestatementnegative.^isneededwhenweuse\wand\sinsmallletters. – AmirZpr Jan29,2019at10:44 3 Doesn'tthisinterpretitsothateitheroutsideworoutsides,andsincethosetwodon'treallyintersectitjustletsthroughallofthecharacters?(Thusnotfilteringanything.) – Zael Feb19,2019at9:20 2 @ZaelYou'reright,theregularexpressionasstated(/[\W\S]/)doesleteverythingthrough.AmoreaccuraterepresentationofwhatIbelieveAmirwasgettingatwouldbe[^\w\s].Intheformer,theregularexpressionissaying"matchanythingthatisnotalphanumericORthatisnotwhitespace",whichasyoumentionedlet'severythingthroughsincealphanumericcharactersarenotwhitespaceandviceversa.Thelattersays"matchanythingthatisnotalphanumericANDthatisnotwhitespace".Ofcourse,exceptionsapplyinthataccentedcharacters(likeÀ)arematchedby[^\w\s]. – Jesse Jan22,2020at7:22 thisdoesn'tincludethe_char – MikeSchem Sep1,2020at21:33 | Show1morecomment 13 Answer /[\W\S_]/ Explanation Thiscreatesacharacterclassremovingthewordcharacters,spacecharacters,andaddingbacktheunderscorecharacter(asunderscoreisa"word"character).Allthatisleftisthespecialcharacters.Capitallettersrepresentthenegationoftheirlowercasecounterparts. \Wwillselectallnon"word"charactersequivalentto[^a-zA-Z0-9_] \Swillselectallnon"whitespace"charactersequivalentto[\t\n\r\f\v] _willselect"_"becausewenegateitwhenusingthe\Wandneedtoadditbackin Share Improvethisanswer Follow editedSep1,2020at21:35 answeredApr23,2020at18:45 MikeSchemMikeSchem 7981212silverbadges2626bronzebadges 4 MikeSchem,youjusttookmethroughatimemachine. – pixelbobby Apr24,2020at2:26 yea,Inoticedit.wasold,butIfeltthesimplestanswerwasn'tposted. – MikeSchem Apr27,2020at16:44 howisthisdifferentfromtheanswerbelowthatfailsonunderscore? – sf8193 Aug20,2020at23:46 1 @MikeSchemYoutravelledaheadoftime.Awesomelysimpleandsweet – ClainDsilva Jul13,2021at11:13 Addacomment | 0 //Thestringmustcontainatleastonespecialcharacter,escapingreservedRegExcharacterstoavoidconflict consthasSpecial=password=>{ constspecialReg=newRegExp( '^(?=.*[!@#$%^&*"\\[\\]\\{\\}<>/\\(\\)=\\\\\\-_´+`~\\:;,\\.€\\|])', ); returnspecialReg.test(password); }; Share Improvethisanswer Follow answeredJul17,2019at21:49 ArniGudjonssonArniGudjonsson 53499silverbadges2323bronzebadges 3 Don'tusetheRegExpconstructorwhenyoucanjustusearegexliteral.Muchlessescapingwork(mostofwhichareunnecessaryanyway),andit'smoreefficientaswell. – Bergi Jul17,2019at21:56 Whyuseacomplicatedlookaheadwhenyoucanjustmatchthecharacterdirectly? – Bergi Jul17,2019at21:58 Canyougiveanexample@Bergi?Idon'tunderstandwhatyouaresuggesting. – ArniGudjonsson Sep18,2019at17:09 Addacomment | 0 Asimplewaytoachievethisisthenegativeset[^\w\s].Thisessentiallycatches: Anythingthatisnotanalphanumericcharacter(lettersandnumbers) Anythingthatisnotaspace,tab,orlinebreak(collectivelyreferredtoaswhitespace) Forsomereason[\W\S]doesnotworkthesameway,itdoesn'tdoanyfiltering.AcommentbyZaelononeoftheanswersprovidessomethingofanexplanation. Share Improvethisanswer Follow answeredOct16,2019at14:14 HarfelJaquezHarfelJaquez 25944silverbadges1010bronzebadges 1 No,theunderscoreismissingandallcharactersoutoftheasciirangeandmostofthecontrolcharactersintheasciirangewouldmatchthisclass./[^\w\s]/.test('é')#true,/[^\w\s]/.test('_')#false. – CasimiretHippolyte Oct18,2019at11:00 Addacomment | 0 Howabout(?=\W_)(?=\S).?Itchecksthatthecharactermatchedbythe.isnotawordcharacter(however_isallowed)andthatit'snotwhitespace. Note:as@CasimiretHippolytepointedoutinanothercomment,thiswillalsomatchcharacterslikeéandsuch.Ifyoudon'texpectsuchcharactersthenthisisaworkingsolution. Share Improvethisanswer Follow answeredJul28,2021at15:43 theDutchFlamingotheDutchFlamingo 1122bronzebadges Addacomment | 0 tobuildupon@jeff-hillmananswer,thisisthecompleteversion /[\\@#$-/:-?{-~!"^_`\[\]]/ Tests functionnoSpecialChars(str){ constmatch=str.match(/[\\@#$-/:-?{-~!"^_`\[\]]/) if(!match)return thrownewError("gotunsupportedcharacters:"+match[0]) } //prettier-ignore constsymbols=["!","@","#","$","%","^","&","*","(",")","-","_","+","=",".",":",";","|","~","`","{","}","[","]","\"","'","","?","/","\\"] symbols.forEach((s)=>{ it(`validatesnosymbol${s}`,async()=>{ expect(()=>{ noSpecialChars(s) }).toThrow(); }) }) Share Improvethisanswer Follow answeredJun23at3:24 goldylucksgoldylucks 4,78633goldbadges3535silverbadges4242bronzebadges Addacomment | -11 Replacealllattersfromanylanguagein'A',andifyouwishforexamplealldigitsto0: returnstr.replace(/[^\s!-@[-`{-~]/g,"A").replace(/\d/g,"0"); Share Improvethisanswer Follow answeredAug28,2017at12:18 YaronLandauYaronLandau 4344bronzebadges 1 30 Whatquestionareyouanswering? – Toto Aug28,2017at12:21 Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedjavascriptjqueryregexoraskyourownquestion. TheOverflowBlog WhyPerlisstillrelevantin2022 Skillsthatpaythebillsforsoftwaredevelopers(Ep.460) FeaturedonMeta Testingnewtrafficmanagementtool Duplicatedvotesarebeingcleanedup Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Linked 1 RegularExpressiontocheckSpecialcharactersexcepthypenandforwardslash 0 RegextoMatch:!$%^&*()_+|~-=`{}[]:";'<>?,./ 2 MicrosoftC++exception:std::regex_erroratmemorylocation 2 std::regexthrowsMicrosoftC++exception:std::regex_erroratmemorylocationonruntime -1 Cansomeonepleasefixitsothatthefunctioncandetectwhethertheinputhasatleastonesymbolinit? 1 HowcanIchangethedirectionoftextareawhenthereisPersiancharacter? 1 Doparentheseschangethelengthofaregularexpression? -1 HowtoputifconditioninJS/JQuerylikeEmailrequiredproperties? 0 Regextovalidateapassword Related 633 Howtomatchalloccurrencesofaregex 1020 Howtovalidatephonenumbersusingregex 4979 Regularexpressiontomatchalinethatdoesn'tcontainaword 466 Regex:matcheverythingbutaspecificpattern 2005 RegExmatchopentagsexceptXHTMLself-containedtags 705 Regextoreplacemultiplespaceswithasinglespace 1202 Negativematchingusinggrep(matchlinesthatdonotcontainfoo) 518 Regextomatchonlyletters 612 RegexMatchallcharactersbetweentwostrings 1002 CheckwhetherastringmatchesaregexinJS HotNetworkQuestions Whyissomuchcurrentgoingfrombasetocollector? Areboysgenerally"lazy"intheirearlyteens? GolfGitHub'sPagerLogic ZenerDiodeTransientBehaviour CanIdeletethisextraMacintoshHD-Datapartition? Partswithnopartnumberhowisitidentified?(needhelp,butforfuturetoo) Howtogetawhitecirclewithablackborderusing"Graphics"? Howtoresignwithmanagementonvacation? NumberofsignificantdigitsinuncertaintyofAround PlayerwantstoplayaStockbroker/Trader.HowdoIImplementalightweighttradingsystem? Whatpumpsbloodthroughalistener'sbody? Importanceofstandardizationofdefinitionsofmathematicalterms Familyofsetswithacoveringproperty Whatdoyouhavetodotosoundlikeyou'reimprovisingwhenyou'reactuallyreadingfromsheetmusic? HowtoputMicrosoftTeamscallonhold? Coloringofagraphrepresentingthepowerset Pheasanthuntingandmanualtransmissiondriving FieldcontainsXandYcoordinates Does'moonlighting'mean'illegalwork'? DoesarelaywithacapacitiveloadstillrequireaMOV? StepsTravellingfromCanadatoSpainwithastopoveratUS(YVR-EWR-PMI) Addintheblanks Isitcorrecttosay"Theboyrolledtheclayintoatubewithhispalms"? Tooltodetecterrorsinapplication'sexecutionlogic morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-js Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1116 - Stack Overflow
The regular expression for this is really simple. Just use a character class. The hyphen is a spe...
- 2Regular Expressions (REGEX): Basic symbols - Scripting Blog
Regular Expressions (REGEX): Basic symbols · Take special properties away from special characters...
- 3Regular expressions 1. Special characters
The following characters are the meta characters that give special meaning to the regular express...
- 4Metacharacters - IBM
- 5Regular Expression (Regex) Tutorial
A range expression consists of two characters separated by a hyphen ( - ). It matches any single ...