Reputation: 3
How would I get a string that is between two other strings?
ex: I have a string <str>hello this is stuff</str>
and I want to get what is between <str>
and </str>
thanks in advance
Upvotes: 0
Views: 1010
Reputation:
Although the title of your question is very bad, I know exactly what you're talking about, and I have had trouble with this before. The solution is using a Pattern.
An easy way to get the string that is between <str>
and </str>
(which I'm guessing will probably just be something different in HTML), is to do this:
First things first initialize a Pattern by doing this:
Pattern pattern = Pattern.compile("<str>(.*?)</str>"); // (.*?) means 'anything'
Then, you want to get a matcher from it, by doing:
Matcher matcher = pattern.matcher(<str>); //Note: replace <str> with your string variable, which contains the <str> and </str> codes (and the text between them).
Next, depending on whether or not you want to find the last occurrence of the match, or the first, or all of them, then do these:
First only
:
if (matcher.find()) { // This makes sure that the matcher has found an occurrence before getting a string from it (to avoid exceptions)
occurrence = matcher.group(1);
}
Last only
:
while(matcher.find()) { // This is just a simple while loop which will set 'n' to whatever the next occurrence is, eventually just making 'n' equal to the last occurrence .
occurrence = matcher.group(1);
}
All of them
:
while(matcher.find()) { // Loops every time the matcher has an occurrence , then adds that to the occurrence string.
occurrence += matcher.group(1) + ", "; //Change the ", " to anything that you want to separate the occurrence by.
}
Hopefully this helped you :)
Upvotes: 3