How to extract a substring using regex - java - Stack Overflow
文章推薦指數: 80 %
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
延伸文章資訊
- 1How can I extract a portion of a string variable using regular ...
We will show some examples of how to use regular expression to extract and/or ... Where n is the ...
- 2Find Substring within a string that begins and ... - Regex Tester
Top Regular Expressions. Url checker with or without http:// or https:// · Match string not conta...
- 3Regex.Match Method (System.Text.RegularExpressions)
Searches an input string for a substring that matches a regular expression pattern and returns th...
- 4Extracting a substring using regular expression matching - IBM
You can use regular expression matching to retrieve a single substring or all substrings from a s...
- 5Simple RegEx Tutorial
Simple RegEx Tutorial. Regular Expression can be used in Content Filter conditions. Regular Expre...