[SOLVED] Extracting hashtags from a sentence given by a user without using list Java


This Content is from Stack Overflow. Question asked by Bobbington

I’m trying to make a program where a user can post a comment and it’ll be able to extract the words i.e I love to #program in #java would show the output


I am unable to find any pointers on how you’d go about to do this using arrays. Do anyone have any suggestion for suitable methods?


I would use regular expressions.

In the below code, the pattern that I search for is a # character followed by one or more lowercase letters which is what I understood from the example in your question. If that is not the case, then you will need to change the pattern. Refer to the documentation and there are also many questions here about regular expressions in Java.

Also note that the below code uses the stream API. Method results was added in JDK 9, so you need at least that version in order to run the below code.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Comments {

    public static void main(String[] strings) {
        String sentence = "I love to #program in #java.";
        Pattern regex = Pattern.compile("#[a-z]+");
        Matcher mtchr = regex.matcher(sentence);
             .forEach(mr -> System.out.println(mr.group()));

The above code produces the following output:


This Question was asked in StackOverflow by Bobbington and Answered by Abra It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?