Java - Regexp group matching exception

I am 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_-]*%\\})" );

      

First I check if the argument is present in the string, then I try to extract the argmument name, and then I replace the whole pattern with the value of the arguments contained in the 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 have tested my reg-exs on an online reg reg tester and they seem to work as intended. But for some reason I am getting an exception when I try to extract the name of the argument using group ():

java.lang.IllegalStateException: No successful match so far

      

What could it be because of? Thank:)

+3


source to share


1 answer


The problem seems to be on this line:

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

      



You call << 21> matcher#group()

before calling methods matcher#find()

or matcher#matches()

.

+4


source







All Articles