Collecting links in a text file

Asked

Viewed 343 times

1

I have a problem in my program where I have to get links in the entire text file. I used regex to collect the links, however, only a few lines are captured (the file has approximately 3500 lines) and some links. Note: The text file is from Whatsapp texts. This is my code so far:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        // TODO add your handling code here:
    File arq;
    //FileWriter saveArq;
    Scanner lerArq;
    try {

        arq = new File("/home/kayck/Documentos/list.txt");
        //saveArq = new FileWriter("/home/kayck/Área de Trabalho/Salvo.txt");
        String listaFinal = "";
        String pattern = "https.*. ";
        Pattern r = Pattern.compile(pattern);
        lerArq = new Scanner(arq, "UTF-8");                      
        Matcher matcher = r.matcher("");
          while (lerArq.hasNextLine()){
            String line = lerArq.nextLine();
            matcher.reset(line);
            while (matcher.find()) {
              System.out.println(matcher.group());
            }
          }

        lerArq.close();
        //saveArq.write(listaFinal);
        //saveArq.close();
        JOptionPane.showMessageDialog(null, "Salvo com sucesso!", "Concluído", JOptionPane.INFORMATION_MESSAGE);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Arquivo não carregado.", "Error", JOptionPane.INFORMATION_MESSAGE);
    } catch (IOException ex) {
        Logger.getLogger(TelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }

}

And here the txt file link: http://pastebin.com/NdFbuBbG

And the exit:

https://chat.whatsapp.com/HZXXYmjcVAY6AZeR34djup 
https://chat.whatsapp.com/LNM1FIhkrAA5kJ5tuwYvO8 [6/11 10:41 PM] +55 74 8844-2659‬: 
https://chat.whatsapp.com/57WiGUbr8JQHvw48bUpD4v só clicar no link pra 
https://chat.whatsapp.com/Cqo7yy6G0WZ0yPKBcxeOQy Vamos de 
https://chat.whatsapp.com/FG0EfM0l7LfCTZhkgcX23F 
https://chat.whatsapp.com/308yhRFusJo2dj94PqONMw [29/10 11:24 PM] +55 21 96680-8612‬: Acesse este link para entrar no meu grupo do WhatsApp: 
https://chat.whatsapp.com/GUBItIHCK84BrnR0LiYoOA 
https://chat.whatsapp.com/8N98Ei6IkzA2jbcgi3diRz quem quiser entra só clica no link 
https://chat.whatsapp.com/30nqyyplmQO2ooTfqMBQiv quem gosta de uma música sertaneja se quiser participar do meu Grupo add ai 
https://chat.whatsapp.com/BiHEx7MZxpG6VN5YQr8jL1  (pra entrar no grupo só clickar no 
https://chat.whatsapp.com/EpxEUAA7VLx1Yr451hiZvH / Se quiser entrar 
https://chat.whatsapp.com/8N98Ei6IkzA2jbcgi3diRz quem quiser entra só clica no link 
https://chat.whatsapp.com/30nqyyplmQO2ooTfqMBQiv quem gosta de uma música sertaneja se quiser participar do meu Grupo add ai 
https://chat.whatsapp.com/BiHEx7MZxpG6VN5YQr8jL1  (pra entrar no grupo só clickar no 
https://chat.whatsapp.com/6ev8xZIsXdIBVuhSrvjs3q *DIVULGA AE PRA 
https://chat.whatsapp.com/JOiJQ2F1hXb39H9kHC3eC9  
https://chat.whatsapp.com/K4tk0xyRAPuHzlLGiMAKNR regras do grupo / nao ofender os participantes do grupo / nao mudar a imagem e nem o nome do grupo /nao enviar correntes /nao mandar pornografias /se nao cumprirem as regras do grupo sera removido/fora isso sejam todos bem vindos e aproveitem o grupo grato pela 
https://chat.whatsapp.com/6vQZWAFDMDR7ao3n7iCWCM regras do grupo pode mandar musicas do legião videos /fazer comentários/pode tambem mandar musicas de outras bandas brasileiras de rock tambem/mais esse grupo e especialmente pra musicas do legião urbana/videos /nao mandar correntes /nao mudar a imagem do grupo e nem o nome / nao mandar pornografias/nao ofender os participantes do grupo se nao sera removido severamente grato pela compreensão ✌viva o rock 
https://chat.whatsapp.com/31JAQmg2vuiIUsrZKpzr5w estou convidando quem torce pelo cruzeiro quem quiser participar regras nao pode ofender um ao outro nao mudar a imagem e nem o nome /nao mandar pornografias e etc porque sera removido blza 
https://chat.whatsapp.com/9Lr02M2PbYy0UBgjfcC5Bq GRUPO PARA FALARMOS DO AMOR DE DEUS PEDIDO DE ORAÇÃO LOUVORES TESTEMUNHOS MENSAGEM DA BÍBLIA EM FIM PRA ESTAMOS SEMPRE EM CONTATO COM 
https://chat.whatsapp.com/FiDg2ArhJJQKT7McjWKeVf lista de reggae proibido mexer na imagem do grupo proibida postar vídeo pornográfico proibida avi para postar imagens erótica proibido entrar no PV sem a permissão proibido xingamento no grupo todas administradora agradece a presença de todos uma boa 
https://chat.whatsapp.com/AMN8bpeaU3X1NX0Sa9Jved 
https://chat.whatsapp.com/0Fnu9cUg29pEQdj6gnSCd0 *APENAS YOUTUBERS* 
https://chat.whatsapp.com/IOBQcd7pzyD3lvB5XlDZEA entra 
https://chat.whatsapp.com/IOBQcd7pzyD3lvB5XlDZEA entra 
https://chat.whatsapp.com/2rXe65aIOUGDlicJDtgNFO 
https://chat.whatsapp.com/FGsOylLncd92Ry51cjUkVT grupo de musica e clips nao e permitido 
https://chat.whatsapp.com/2rXe65aIOUGDlicJDtgNFO entra 
https://chat.whatsapp.com/BmRP999uOkL5HWy6eAUave  
https://chat.whatsapp.com/7FiKSYAMPOvBhHKGbBZG1W grupo eróticos, hétero e gls.  Proibido entradas de menores de 18 anos. Proibido postagens de coerentes bíblicas, proibido postagens de links, proibido mudar as configurações do grupo. Sejam bem vindos e divirtam 
https://chat.whatsapp.com/L0JXUA040ES6Gvda1CHOoV grupo para vendas e 
https://chat.whatsapp.com/FsVkX8QXcMa9b2258UcZ7E   
https://chat.whatsapp.com/HgPx1FK41QvJUBJSdAJnTW 
https://chat.whatsapp.com/1gqTeuimf2GInmWQv2oB4R 
https://chat.whatsapp.com/CsRM8fEDaZaLQzZ68bUN7E grupo só para fazer novas amizades sem 
https://chat.whatsapp.com/EKOLpMWPwuFADe9Zlut67A *pra quem shippa* obrigada 
https://chat.whatsapp.com/BV3rek5lRK67tZlWlgfsZX  ven te invitó a formar parte del 
https://chat.whatsapp.com/CcyQoCADl837zH3dYXVaZg    brota

1 answer

1

Using a simple logic.

Every Url starts with http and ends at the first space.

You can use the pattern: .*(http[^ ]+).*

Since you have multiple lines, but the urls are not broken into 2 lines, use the modifier m (Java Pattern.MULTILINE) to define that each line is independent of each other.

With this you can do so much by replace $1 and change the content of the lines, keeping only the url.

Or by match, where the url will be in group 1 of match.

  • Good! I solved using " b(https://chat) .? [ s]+", but I’ll remember this one!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.