Reputation: 8335
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 :)
Upvotes: 4
Views: 661
Reputation: 785541
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.
Upvotes: 5