I'm trying to come up with a regex pattern for this but to no avail. Here are some examples of what I need.
[]
Hello $World
[$World]
My name is $John Smith and I like $pancakes
[$John, $pancakes]
String test = "My name $is John $Smith";
String[] testSplit = test.split("(\\$\\S+)");
System.out.println(testSplit);
[My name , John ]
split
takes a regex, and specifically splits the string around that regex, so that what it splits on is not retained in the output. If you want what it found to split around, you should use the Matcher
class, for example:
String line = "My name $is John $Smith";
Pattern pattern = Pattern.compile("(\\$\\S+)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
This will find all the matches of a pattern in a String and print them out. These are the same strings that split
will use to divide up a string.