简体   繁体   中英

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)

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.

split just uses your pattern to separate strings. If you want to return the matched string, try something like this:

String test = "My name $is John $Smith";
Pattern patt = Pattern.compile("(\\$\\S+)");
Matcher matcher = patt.matcher(test);
while (matcher.find()) {
    System.out.println(matcher.group()); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM