Problemas com expressão regular

12 respostas
G

public void splitChapters(String[] sentences_str) { Integer num1 = 1, num2 = 2, ic = 0, i = 0; String[] chapterArray = new String[sentences_str.length]; Boolean atribuiSentences = false, continuar = false; Pattern inicioPadrao = Pattern.compile("..?C H A P T E R..?"+num1.toString()+"[^\\d].?",Pattern.CASE_INSENSITIVE); //Matcher inicioMatcher = inicioPadrao.matcher(sentences_str[i]); Pattern fimPadrao = Pattern.compile("(..?C H A P T E R..?"+num2.toString()+"[^\\d].?)|(A-1..?APPENDIX)",Pattern.CASE_INSENSITIVE); //Matcher fimMatcher = fimPadrao.matcher(sentences_str[i]); javax.swing.JOptionPane.showMessageDialog(null,"("+inicioPadrao.pattern()+")\n("+fimPadrao.pattern()+")"); do { System.out.print("\n"+i); if(sentences_str[i].matches(inicioPadrao.pattern()))System.out.print(" inicio"); if(sentences_str[i].matches (fimPadrao.pattern()) )System.out.print("fim\ i ++; }while(i < sentences_str.length); }

12 Respostas

DaniloAndrade

Qual o problema?

paulohms

geazy, qual é a sua dúvida ? o que está ocorrendo ?

G

desculpe, descuido meu. Eu estou buscando num array Onde determinada posicao tera os padroes que eu determinei em inicioPadrao e fimPadrao. mas os matches nao retorna verdadeiro de jeito nenhum. Eu testei em testadores de regex e minha expressão regular funcionou. mas nao funciona no programa.

E

Você não leu a documentação

matches - a string tem que bater com a expressão regular inteira
find - basta você achar a expressão regular dentro da string

Por exemplo, digamos que você tenha a expressão regular “tipl”.

Então:

String str = "múltipla";
Matcher mat = Pattern.compile ("tipl").matcher (str);
System.out.println (mat.matches()); // retorna "false"
System.out.println (mat.find()); // retorna "true"
G

Na verdade eu entendi errado. Mas eu ja tentei con o find() e tb deu errado;

E

Por que é que deu errado?

G
public void splitChapters(String[] sentences_str)
   {
      Chapter chapterArrayer[] = new Chapter[sentences_str.length];
      Integer num1 = 1, num2 = 2, ic = 0, i = 0;
      String[] chapterArray = new String[sentences_str.length];
      Boolean atribuiSentences = false, continuar = false;
      Pattern inicioPadrao = 
        Pattern.compile("..?C H A P T E R..?"+num1.toString()+"[^\\d].?",Pattern.CASE_INSENSITIVE);
      Matcher inicioMatcher = inicioPadrao.matcher(sentences_str[i]);
      Pattern fimPadrao = 
        Pattern.compile("(..?C H A P T E R..?"+num2.toString()+"[^\\d].?)|(A-1..?APPENDIX)",Pattern.CASE_INSENSITIVE);
      Matcher fimMatcher = fimPadrao.matcher(sentences_str[i]);
      javax.swing.JOptionPane.showMessageDialog(null,"("+inicioPadrao.pattern()+")\n("+fimPadrao.pattern()+")");
      do
      {
         if(inicioMatcher.find())System.out.print("\ninicio");
         if(fimMatcher.find())System.out.print("fim\n");      
         i ++;
      }while(i < sentences_str.length);
   }

Tentei assim. E mesmo assim nao rodou?

E

Seu problema é que você não imprimiu o que estava sendo examinado pelo matcher, para ver se ele estava mudando.
Obviamente você não pode fazer esse tipo de macumba que você fez (mudar o índice e achar que tudo se muda magicamente). Harry Potter tem limites.

Eu só peguei seu código, não o testei, mas acho que o que acertei abaixo deve ser mais correto.

package guj;

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

class Chapter{
    // só incluí isto para poder compilar
}

public class TesteRegex3 {

    public void splitChapters(String[] sentences_str) {
        Chapter chapterArrayer[] = new Chapter[sentences_str.length];
        Integer num1 = 1, num2 = 2, ic = 0, i = 0;
        String[] chapterArray = new String[sentences_str.length];
        Boolean atribuiSentences = false, continuar = false;
        Pattern inicioPadrao = Pattern.compile("..?C H A P T E R..?" + num1.toString() + "[^\\d].?", Pattern.CASE_INSENSITIVE);
        // Aqui só estou pondo uma string vazia, para iniciar o objeto Matcher. 
        Matcher inicioMatcher = inicioPadrao.matcher("");
        Pattern fimPadrao = Pattern.compile("(..?C H A P T E R..?" + num2.toString() + "[^\\d].?)|(A-1..?APPENDIX)",
            Pattern.CASE_INSENSITIVE);
        // Aqui só estou pondo uma string vazia, para iniciar o objeto Matcher. 
        Matcher fimMatcher = fimPadrao.matcher("");
        javax.swing.JOptionPane.showMessageDialog(null, "(" + inicioPadrao.pattern() + ")\n(" + fimPadrao.pattern() + ")");
        do {
            // Note que o matcher não consegue "andar" sobre o índice i. Você tem de 
            // inicializá-lo com "reset" do jeito que fiz abaixo
            inicioMatcher.reset(sentences_str[i]);
            if (inicioMatcher.find())
                System.out.print("\ninicio");
            fimMatcher.reset(sentences_str[i]);
            if (fimMatcher.find())
                System.out.print("fim\n");
            i++;
        }
        while (i < sentences_str.length);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}
G

vlw cara. Eu realmente achei q o garbage collector ia fazer o servico pra mim heheh. mas ta bom, adiquiri experiencia neste processo.

G

E quanto ao Pattern.Compile() : eu posso dar um num loop sem problemas? terei q iterar o num1 e num2…

E

O que o faxineiro (garbage collector) tem a ver com o projetista do cinema (seu programa)? Não ache que o garbage collector substitui seu cérebro :slight_smile:

E

Depende de que lugar do loop ele está - se o Pattern.compile for executado só a cada mudança de capítulo não deve haver problemas.

Criado 29 de janeiro de 2013
Ultima resposta 29 de jan. de 2013
Respostas 12
Participantes 4