Parsing de String com variáveis

2 respostas
danieldestro

Houston, we have a problem.

Tenho uma String do tipo: “$id - $nome” e um objeto.

Quero substituir essas variávies da minah String com o valor das propriedades desse objeto, ou seja, onde está “$id” ele substitui pelo valor do objeto.getId().

Só que, primeiro, eu preciso extrair todas essas variáveis. Pensei em usar Regular Expression.

Alguém tem idéia de como fazer isso?

Lí a documentação da API do Java, mas to sem uma luz.

Valeu!

2 Respostas

smota

Para extrair todas as variáveis a RE ($[a-zA-Z]*) resolve, ela vai retornar cada $foo como um grupo e ai vc remove o $ do inicio e com reflection só chama o getFoo() … o código é bastante simples … dá uma brincada ai com a classe Matcher.

danieldestro

Ecola:

private String[] extractVariables( String text ) {
        ArrayList list = new ArrayList();
        Matcher matcher = Pattern.compile("[$][a-zA-Z0-9]+").matcher( text );
        while( matcher.find() ) {
            String contents = matcher.group();
            list.add( contents.substring(1) );
        }
        String[] variables = new String[ list.size() ];
        list.toArray( variables );
        return variables;
    }


    private String parseText( Object obj, String text ) {
        if( text == null ) {
            return obj.toString();
        }

        String[] variables = extractVariables( text );
        if( variables == null ) {
            return obj.toString();
        }
        Method meth = null;
        Object retobj = null;
        String methName = null;
        for( int i=0; i<variables.length; i++ ) {
            try {
                methName = "get" + variables[i].substring(0,1).toUpperCase() + variables[i].substring(1);
                meth = obj.getClass().getMethod( methName, new Class[0] );
                retobj = meth.invoke( obj, new Object[0] );
            } catch( Exception e ) {
                e.printStackTrace();
            }
            text = text.replaceFirst( "[$]"+variables[i], retobj.toString() );
        }
        
        return text;
    }
Criado 5 de outubro de 2004
Ultima resposta 5 de out. de 2004
Respostas 2
Participantes 2