4

I'm trying to create some templates inside an XML file, and i want to have arguments with the following syntax :

{%test%} where "test" is the name of the argument.

private static final Pattern _hasArgPattern = Pattern.compile( "\\{%[a-zA-Z0-9_-]*%\\}" );

private static final Pattern _getArgNamePattern = Pattern.compile( "\\{%([a-zA-Z0-9_-]*)%\\}" );

private static final Pattern _replaceArgPattern = Pattern.compile( "(\\{%[a-zA-Z0-9_-]*%\\})" );

I first check if an argument is present in the string, then I attempt to extract the argmument's name, and then I replace the whole pattern by the arguments value contained in an HashMap :

    if( _hasArgPattern.matcher( attr ).matches() )
    {
        String argName = _getArgNamePattern.matcher( attr ).group( 1 );

        if( ! args.containsKey( argName ) )
        {
            throw new Exception( "Argument \"" + argName + "\" not found." );
        }

        return _replaceArgPattern.matcher( attr ).replaceFirst( args.get( argName ) );
    }
    else
    {
        return attr;
    }

I tested my reg exps on an online reg exp tester and they seemd to work as intented. But for some reason I'm getting an exception when trying to extract the name of the argument using group() :

java.lang.IllegalStateException: No successful match so far

What can this be due to ? Thank you :)

1 Answer 1

5

Problem seems to be on this line:

String argName = _getArgNamePattern.matcher( attr ).group( 1 );

You cannot call matcher#group() before calling matcher#find() or matcher#matches() methods.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help ! I assume i can get rid of the first pattern then. EDIT : It works.
You cannot get rid of it, otherwise how will you get argName populated? Just call find or matches as I suggested before using group.
Also be careful with the args.get(argName) it might contain $ or \ characters.
Yes. I could also get rid of the first regexp. Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.