Morgan Morgan - 1 month ago 13
Java Question

Regex to match $ symbol followed by any word and keep the word

I'm trying to come up with a regex pattern for this but to no avail. Here are some examples of what I need.

[]
represents an array as output.

Input

Hello $World


Output

[$World]


Input

My name is $John Smith and I like $pancakes


Output

[$John, $pancakes]


I managed to come up with this, it matches the pattern but doesn't keep the words it finds.

String test = "My name $is John $Smith";
String[] testSplit = test.split("(\\$\\S+)");
System.out.println(testSplit);


Output

[My name , John ]


As you can see, it's completely swallowing the words I need, more specifically, the words that match the pattern. How can I have it return an array with only the words I need? (as shown in the examples)

Answer Source

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.