0
respostas

[Projeto] Extraindo hashtags de um texto

Olá!

Segue minha resolução:

  • Classe texto com o método extrairHashtag que verificas as # via Pattern e Matcher, organiza em uma lista e imprime:
package b.com.alura.exercicios;

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

public class Texto {

    private String texto;

    public void setTexto(String texto) {
        this.texto = texto;
    }

    public void extrairHashtags(){

        Pattern pattern = Pattern.compile("#(\\w+)");
        Matcher matcher = pattern.matcher(texto);
        List<String> hashtags = new ArrayList<>();
        while (matcher.find()){
            hashtags.add("#" + matcher.group(1));
        }

        String resultado = String.join(", ", hashtags);

        System.out.println("Hashtags encontradas: " + resultado);


    }
}
  • Main para rodar a aplicação:
package b.com.alura.exercicios;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        Texto texto = new Texto();
        System.out.println("Digite o texto: ");
        texto.setTexto(sc.nextLine());
        texto.extrairHashtags();

    }
}