Expressão regular ? salvar o valor em uma string

2 respostas
A
Pessoal, bom dia.
String resultado = "";
Pattern pega = Pattern.compile("*index of");
    Matcher m = pega.matcher(texto);

    while (m.find()) {  
    //que codigo uso para salvar?
    }  
    }
Estou querendo salvar na String resultado tudo que vier antes do termo : "index of" da String texto. Estava tentando usar a expressão regular: *index of, só que nunca acha nada.

Alguém pode me ajudar a construir uma expressão regular que se aplique ao meu caso e também a salvar tudo que vem antes de "index of" na string resultado?

Grato

2 Respostas

Andre_Fonseca

oi,

veja se ajuda

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

public class Main {
  public static void main(String[] argv) throws Exception {
    Pattern end = Pattern.compile("\G\z");
    Matcher mat = end.matcher("this is a test 999");
    if (mat.find())
      System.out.println(mat.group());
  }
}

http://www.java2s.com/Code/Java/Regular-Expressions/Matchstringends.htm

M

substring() resolve seu problema. Com regex é possível, porém fica mais feio e menos legível:

// com substring (cuidado!! se não houver 'index of' na frase ele
// retorna -1 e vai dar erro)                                    
String frase = "3 is the index of 'u' in 'house'";               
String resultado = frase.substring(0, frase.indexOf("index of"));
System.out.println(resultado);                                   
// com regex                                                     
Pattern p = Pattern.compile(".+index of");                       
Matcher m = p.matcher(frase);                                    
if (m.find()) {                                                  
	System.out.println(m.group().replace("index of", ""));       
}
Criado 27 de dezembro de 2009
Ultima resposta 28 de dez. de 2009
Respostas 2
Participantes 3