How to extract a substring using regex - java - Stack Overflow

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

While substring looks for a specific string or value, regex looks for a format. It's more and more dynamic. You need regex, if you are looking for a pattern ... 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 Howtoextractasubstringusingregex AskQuestion Asked 11years,5monthsago Modified 1year,8monthsago Viewed 893ktimes 470 93 Ihaveastringthathastwosinglequotesinit,the'character.InbetweenthesinglequotesisthedataIwant. HowcanIwritearegextoextract"thedataiwant"fromthefollowingtext? mydata="somestringwith'thedataiwant'inside"; javaregexstringtext-extraction Share Follow editedJun20,2014at18:42 Templar 1,79577goldbadges2828silverbadges4040bronzebadges askedJan11,2011at20:22 asdasdasdasd 4,89922goldbadges1515silverbadges77bronzebadges Addacomment  |  14Answers 14 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 690 Assumingyouwantthepartbetweensinglequotes,usethisregularexpressionwithaMatcher: "'(.*?)'" Example: Stringmydata="somestringwith'thedataiwant'inside"; Patternpattern=Pattern.compile("'(.*?)'"); Matchermatcher=pattern.matcher(mydata); if(matcher.find()) { System.out.println(matcher.group(1)); } Result: thedataiwant Share Follow editedMay6,2016at11:05 holmis83 15.1k44goldbadges7676silverbadges8282bronzebadges answeredJan11,2011at20:27 MarkByersMarkByers 771k178178goldbadges15451545silverbadges14361436bronzebadges 10 13 damn..ialwaysforgetaboutthenongreedymodifier:( – MihaiToader Jan11,2011at20:28 41 replacethe"if"witha"while"whenyouexpectmorethanoneoccurences – OneWorld Aug7,2012at16:25 22 mindthatmatcher.find()isneededforthiscodesampletowork.failingtocallthismethodwillresultina"Nomatchfound"exceptionwhenmatcher.group(1)iscalled. – rexford Jul31,2014at14:03 27 @mFontouragroup(0)wouldreturnthecompletematchwiththeouter''.group(1)returnswhatisin-betweenthe''withoutthe''themselves. – tagy22 Feb19,2015at14:34 6 @Larrythisisalatereply,but?inthiscaseisnon-greedymodifier,sothatforthis'is'my'data'withquotesitwouldstopearlyandreturnisinsteadofmatchingasmanycharactersaspossibleandreturnis'my'data,whichisthedefaultbehavior. – Timekiller Sep12,2016at14:08  |  Show5morecomments 81 Youdon'tneedregexforthis. Addapachecommonslangtoyourproject(http://commons.apache.org/proper/commons-lang/),thenuse: StringdataYouWant=StringUtils.substringBetween(mydata,"'"); Share Follow editedJan25,2014at21:13 Yang 7,35277goldbadges4545silverbadges6464bronzebadges answeredMar13,2013at20:37 BeothornBeothorn 1,2781010silverbadges1919bronzebadges 4 13 Youhavetotakeintoaccounthowyoursoftwarewillbedistributed.Ifitissomethinglikeawebstartit'snotwisetoaddApachecommonsonlytousethisonefunctionality.Butmaybeitisn't.BesidesApachecommonshasalotmoretooffer.Eventoughit'sgoodtoknowregex,youhavetobecarefullonwhentouseit.Regexcanbereallyhardtoread,writeanddebug.Givensomecontextusingthiscouldbethebettersolution. – Beothorn Apr13,2015at14:41 4 SometimesStringUtilsisalreadythere,inthosecasesthissolutionismuchcleanerandreadable. – GáborNagy Sep14,2016at11:58 9 Itslikebuyingacartotravel5miles(whenyouaretravelingonlyonceinayear). – prayagupa Mar1,2017at20:38 Whilesubstringlooksforaspecificstringorvalue,regexlooksforaformat.It'smoreandmoredynamic.Youneedregex,ifyouarelookingforapatterninsteadofaspecialvalue. – burak Sep19,2017at10:20 Addacomment  |  18 importjava.util.regex.Matcher; importjava.util.regex.Pattern; publicclassTest{ publicstaticvoidmain(String[]args){ Patternpattern=Pattern.compile(".*'([^']*)'.*"); Stringmydata="somestringwith'thedataiwant'inside"; Matchermatcher=pattern.matcher(mydata); if(matcher.matches()){ System.out.println(matcher.group(1)); } } } Share Follow answeredJan11,2011at20:40 SeanMcEligotSeanMcEligot 18744bronzebadges 3 3 System.out.println(matcher.group(0));whereMatchResultrepresentstheresultofamatchoperationandofferstoreadmatchedgroupsandmore(thisclassisknownsinceJava1.5). Stringstring="Somestringwith'thedataIwant'insideand'anotherdataIwant'."; Patternpattern=Pattern.compile("'(.*?)'"); pattern.matcher(string) .results()//Stream .map(mr->mr.group(1))//Stream-the1stgroupofeachresult .forEach(System.out::println);//printthemout(orprocessinotherway...) Thecodesnippetaboveresultsin: thedataIwant anotherdataIwant Thebiggestadvantageisintheeaseofusagewhenoneormoreresultsisavailablecomparedtotheproceduralif(matcher.find())andwhile(matcher.find())checksandprocessing. Share Follow editedOct16,2020at9:04 answeredOct15,2020at22:28 NikolasCharalambidisNikolasCharalambidis 35.6k1212goldbadges8585silverbadges157157bronzebadges Addacomment  |  8 StringdataIWant=mydata.replaceFirst(".*'(.*?)'.*","$1"); Share Follow answeredSep13,2017at8:28 ZehnVon12ZehnVon12 3,71633goldbadges1818silverbadges2323bronzebadges 1 Canyouexplainyouranswer?LikewhyusereplaceFirst?Why$1? – Elikill58 Jun28at16:01 Addacomment  |  4 asinjavascript: mydata.match(/'([^']+)'/)[1] theactualregexpis:/'([^']+)'/ ifyouusethenongreedymodifier(asperanotherpost)it'slikethis: mydata.match(/'(.*?)'/)[1] itiscleaner. Share Follow answeredJan11,2011at20:26 MihaiToaderMihaiToader 11.8k11goldbadge2828silverbadges3333bronzebadges Addacomment  |  2 StringdataIWant=mydata.split("'")[1]; SeeLiveDemo Share Follow editedAug18,2017at13:08 answeredAug16,2017at13:15 ZehnVon12ZehnVon12 3,71633goldbadges1818silverbadges2323bronzebadges 0 Addacomment  |  1 InScala, valticks="'([^']*)'".r ticksfindFirstInmydatamatch{ caseSome(ticks(inside))=>println(inside) case_=>println("nothing") } for(ticks(inside)matchesEmail=newArrayList<>(); while(m.find()){ Strings=m.group(); if(!matchesEmail.contains(s)) matchesEmail.add(s); } Log.d(TAG,"emails:"+matchesEmail); Share Follow answeredFeb9,2020at20:51 NoahMohamedNoahMohamed 6611silverbadge88bronzebadges Addacomment  |  0 addapache.commonsdependencyonyourpom.xml org.apache.commons commons-io 1.3.2 Andbelowcodeworks. StringUtils.substringBetween(Stringmydata,String"'",String"'") Share Follow answeredFeb27,2020at10:39 GaneshGanesh 56766silverbadges1010bronzebadges Addacomment  |  0 Somehowthegroup(1)didntworkforme.Iusedgroup(0)tofindtheurlversion. PatternurlVersionPattern=Pattern.compile("\\/v[0-9][a-z]{0,1}\\/"); Matcherm=urlVersionPattern.matcher(url); if(m.find()){ returnStringUtils.substringBetween(m.group(0),"/","/"); } return"v0"; Share Follow answeredJun10,2020at13:11 ArindamArindam 60766silverbadges1313bronzebadges Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaregexstringtext-extractionoraskyourownquestion. TheOverflowBlog WhyPerlisstillrelevantin2022 Skillsthatpaythebillsforsoftwaredevelopers(Ep.460) FeaturedonMeta Testingnewtrafficmanagementtool Duplicatedvotesarebeingcleanedup Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Linked -1 REGEXmustincludesubstring -1 Regexexpressiontocapturetextafteracharacterandterminatedbywhitespace -4 Howtoextractstringbetweendoublequotesinjava? 0 Javasplitastringbyusingaregex 1 Regex:Howtomatchentirestringwhilecapturingindividualgroups -4 Java,getspecificStringfromFile 55 Howtoextractastringbetweentwodelimiters 4 ExtractletterfromStringcharactersandnumbers 4 UsingAndroidPatternandMatcherclass(Regex) 4 Java-cutstringinaspecificway Seemorelinkedquestions Related 3868 HowcanIvalidateanemailaddressusingaregularexpression? 3213 HowtocheckifastringcontainsasubstringinBash 4534 HowdoIread/convertanInputStreamintoaStringinJava? 943 ExtractsubstringinBash 1751 Howdoyouuseavariableinaregularexpression? 1662 startsWith()andendsWith()functionsinPHP 5198 HowtoreplacealloccurrencesofastringinJavaScript 7414 HowtocheckwhetherastringcontainsasubstringinJavaScript? 3589 DoesPythonhaveastring'contains'substringmethod? 1856 HowtosplitastringinJava HotNetworkQuestions Partswithnopartnumberhowisitidentified?(needhelp,butforfuturetoo) HowmanyRussianssayAlaskaisrightfullytheirs? UnusualroutesfromUKtoDenmark Ifnuclearweaponswereneverexistedorinvented,whatcouldreplaceit CanIdeletethisextraMacintoshHD-Datapartition? Howtostabilizethisbookshelf NumberofsignificantdigitsinuncertaintyofAround Whatiswrongwithtreatingeverythingasahyperparameter? HowtomanageexhaustionwhenusingGrittyRealism? Howtogetawhitecirclewithablackborderusing"Graphics"? Familyofsetswithacoveringproperty Pheasanthuntingandmanualtransmissiondriving Isitlegaltobreakintoalockedcartogetachildoutinhotweather? Howistimemeasuredinparticleexperiments? HowcanIfindthefunctionnamewhilenavigatingcode? Importanceofstandardizationofdefinitionsofmathematicalterms Onehotlegtoneutralof4-prongdryerreading240voltsandotherhotlegtoneutralreading0volts Mathbbfontforlowercaseletters IsthereanypossibilitythatCERN'sLargeHadronColliderrun3canbedevastating? Whydoesawk-Fworkformostletters,butnotfortheletter"t"? Useof"Audacity"forteachingundergraduatelabsofdigitalsignalprocessing? StepsTravellingfromCanadatoSpainwithastopoveratUS(YVR-EWR-PMI) Children'sbookwith"aring,astone,afingerbone" Contractiblesubcomplexcontaining1-skeleton? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-java Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?