Reputation: 1826
If I wanted to pull all substrings between two characters(general) along a String how would I do that? I also want to keep the first char I match but not the second one.
So, for example, if I wanted ot keep the characters between a #
char and either the next whitespace OR next of another char (in this case #
again, but could be anything) and I had a string, say : "hello i'm #chilling#likeAVillain but like #forreal"
How would I get, say a Set of [#chilling, #likeAVillain, #forreal]
I'm having difficulty because of the either/or end substring case - I want the substring starting with #
and ending before the first occurence of either another #
or a whitespace (or the end of the string if neither of those are found)
Put simplest in sudocode:
for every String W between [char A, either (char B || char C)) // notice [A,B) - want the
//first to be inclusive
Set.add(W);
Upvotes: 2
Views: 2284
Reputation: 124265
This regex #\\w+
seems to do what you need. It will find #
and all alphanumeric characters after it. Since whitespace is not part of \\w
it will not be included in your match.
String s = "hello i'm #chilling#likeAVillain but like #forreal";
Pattern p = Pattern.compile("#\\w+");
Matcher m = p.matcher(s);
while (m.find())
System.out.println(m.group());
output:
#chilling
#likeAVillain
#forreal
Upvotes: 3
Reputation: 732
public static void main(String[] args) throws Exception{
String s1 = "hello i'm #chilling#likeAVillain but like #forreal";
String[] strArr = s1.split("\\#");
List<String> strOutputArr = new ArrayList<String>();
int i = 0;
for(String str: strArray){
if(i>0){
strOutputArray.add("#" + str.split("\\s+")[0]);
}
i++;
}
System.out.println(strOutputArray.toString());
}
Upvotes: 0