Regular expression issues in .net 6 value converter

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

There are some missing parts in your regular expression, for example it doesn't have the curly braces { and } escaped, since curly braces ... 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 Regularexpressionissuesin.net6valueconverter AskQuestion Asked 3monthsago Modified 3monthsago Viewed 97times 0 Iamtryingtolearnsome.net6andc#andIamstrugglingwithregularexpressionsalot.MorespecificalywithAvaloniainWindowsifthatisrelevant. Iamtryingtodoasmallappwith2textboxes.Iwritetextononeandgetthetext"filtered"intheotheroneusingavalueconverter. Iwouldliketofiltermathexpressionstotrytosolvethemlateron.Somethingsimple,kindofawayofwritingtextmathandgettingresultsrealtime. Ihavebeentryingforseveralweekstofigurethisregularexpressiononmyownwithnosuccesswhatsoever. Iwouldliketoreplaceinmystring"_Expression{BLABLA}"for"BLABLA".FortestingmyexpressionsIhavebeencheckinginhttp://regexstorm.net/andhttps://regex101.com/andaccordingtothemmymatchesshouldbecorrect(unlessImisunderstoodtheresults).ButtheresultsinmylittleappareextremelyoddtomeandIfinallydecidedtoaskforhelp. Hereismycode: privatestaticstring?FilterStr(objectvalue) { if(valueisstringstr) { stringpattern=@"\b_Expression{(.+?)\w*}"; Regexrgx=new(pattern); foreach(Matchmatchinrgx.Matches(str)) { stringaux=""; aux=match.Value; aux=Regex.Replace(aux,@"_Expression{",""); aux=Regex.Replace(aux,@"[\}]",""); str=Regex.Replace(str,match.Value,aux); } returnnewstring(str); } returnnull; } Thentheresultsforsomesampleinputsare: Input: Sometext _Expression{x} _Expression{1} _Expression{4} _Expression{4.5}_Expression{4+4} _Expression{4-4}_Expression{4*x} _Expression{x/x} _Expression{x^4} _Expression{sin(x)} Output: Sometext x 1{1} 1{4} 1{4.5}1{4+4} 1{4-4}1{4*x} 1{x/x} 1{x^4} 1{sin(x)} or Input: Sometext _Expression{x} _Expression{4} _Expression{4.5}_Expression{4+4} _Expression{4-4}_Expression{4*x} _Expression{x/x} _Expression{x^4} _Expression{sin(x)} Output: Sometext x _Expression{4} 4.5_Expression{4+4} 4-4_Expression{4*x} x/x _Expression{x^4} _Expression{sin(x)} Itfeelsveryconfusingtomethisbehaviour.Ican'tseewhy"(.+?)"doesnotworkwithsomeofthemanditdoeswithothers...OrmaybeIhaven'tdefinedsomethingproperlyormyReplaceiswrong?Ican'tseeit... Thanksalotforthetime!:) c#regex.net-6.0ivalueconverter Share Follow askedMar15at10:47 JorgeLLJorgeLL 311bronzebadge Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 0 Therearesomemissingpartsinyourregularexpression,forexampleitdoesn'thavethecurlybraces{and}escaped,sincecurlybraceshaveaspecialmeaninginaregularexpression;theyareusedasquantifiers. Usetheonebelow. Forextractingthemathexpressionbetweenthecurlybraces,itusesanamedcapturinggroupwithnamemathExpression. _Expression\{(?.+?)\} _Expression\{:startwiththefixedtext_Expression{ (?:startanamedcapturinggroupwithnamemathExpression .+?:takethenextcharactersinanongreedyway ):endthenamedcapturinggroup \}:endwiththefixedcharacter} Thebelowexamplewilloutput2matches Regexregex=new(@"_Expression\{(?.+?)\}"); varmatches=regex.Matches(@"_Expression{4.5}_Expression{4+4}"); foreach(Matchmatchinmatches.Where(o=>o.Success)) { varmathExpression=match.Groups["mathExpression"]; Console.WriteLine(mathExpression); } Output 4.5 4+4 Share Follow editedMar16at19:26 answeredMar15at23:09 pfxpfx 15.5k4141goldbadges3636silverbadges5252bronzebadges 1 Itworksperfectly.Thanksforthesolutionandthedetailedexplanationpfx,Ican'tbegratefulenough! – JorgeLL Mar16at8:05 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?Browseotherquestionstaggedc#regex.net-6.0ivalueconverteroraskyourownquestion. TheOverflowBlog WhyPerlisstillrelevantin2022 Skillsthatpaythebillsforsoftwaredevelopers(Ep.460) FeaturedonMeta Testingnewtrafficmanagementtool Duplicatedvotesarebeingcleanedup Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Related 1112 Istherearegularexpressiontodetectavalidregularexpression? 3868 HowcanIvalidateanemailaddressusingaregularexpression? 737 RegularExpressionforalphanumericandunderscores 4979 Regularexpressiontomatchalinethatdoesn'tcontainaword 1626 HowdoyouaccessthematchedgroupsinaJavaScriptregularexpression? 1751 Howdoyouuseavariableinaregularexpression? 393 Convertinguserinputstringtoregularexpression 732 Regularexpressiontostopatfirstmatch 2225 Whatisanon-capturinggroupinregularexpressions? 190 Matchmultilinetextusingregularexpression HotNetworkQuestions Partswithnopartnumberhowisitidentified?(needhelp,butforfuturetoo) Areboysgenerally"lazy"intheirearlyteens? Whydoesawk-Fworkformostletters,butnotfortheletter"t"? Isthereanycontextinwhichthe2ndpersonsingularandthe2ndpersonpluraldiffermorphosyntactically? Isitlegaltobreakintoalockedcartogetachildoutinhotweather? Howtostabilizethisbookshelf DeterminedvsUniquelyDetermined HowcanIfindthefunctionnamewhilenavigatingcode? Coloringofagraphrepresentingthepowerset Onehotlegtoneutralof4-prongdryerreading240voltsandotherhotlegtoneutralreading0volts Short-termcapitalgainstaxoncryptocurrency Howistimemeasuredinparticleexperiments? Whatiswrongwithtreatingeverythingasahyperparameter? Whatpumpsbloodthroughalistener'sbody? Whatisthemeaningof"reflecting"inthiscontext? Addintheblanks Ifnuclearweaponswereneverexistedorinvented,whatcouldreplaceit SchengentouristicvisafromFrenchembassybutwanttomakethefirstentryinanotherSchengencountryAustria UnusualroutesfromUKtoDenmark DoesarelaywithacapacitiveloadstillrequireaMOV? PlayerwantstoplayaStockbroker/Trader.HowdoIImplementalightweighttradingsystem? Is"vehicle"really"транспортнийзасіб"?Dopeoplesaythat? Isitethicaltomakeananonymousrefereerealizeweknowwhoheis? Movieaboutafamilylivingonafloatingislandthathadships morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?