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);
}
Problemas com expressão regular
12 Respostas
Qual o problema?
geazy, qual é a sua dúvida ? o que está ocorrendo ?
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.
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"
Na verdade eu entendi errado. Mas eu ja tentei con o find() e tb deu errado;
Por que é que deu errado?
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?
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
}
}
vlw cara. Eu realmente achei q o garbage collector ia fazer o servico pra mim heheh. mas ta bom, adiquiri experiencia neste processo.
E quanto ao Pattern.Compile() : eu posso dar um num loop sem problemas? terei q iterar o num1 e num2…
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 
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.