Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the words start from a special character java

Tags:

java

regex

I want to find the words that start with a "#" sign in a string in java. There can be spaces between the sign and the word as well.

The string "hi #how are # you" shall give the output as :

how
you

I have tried this with regex, but still could not find a suitable pattern. Please help me on this.

Thanks.

like image 662
gishara Avatar asked Feb 02 '23 21:02

gishara


1 Answers

Use #\s*(\w+) as your regex.

String yourString = "hi #how are # you";
Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(yourString);
while (matcher.find()) {
  System.out.println(matcher.group(1));
}

This will print out:

how
you
like image 74
ide Avatar answered Feb 05 '23 16:02

ide