我有以下类PlaceHolderConverter
用于将字符串解析"my {} are beautiful"
为带有填充变量的字符串。
例如new PlaceHolderConverter("\\{\\}").format("my {} are beautiful", "flowers")
将返回字符串"my flowers are beautiful"
。
package something;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PlaceHolderConverter
{
public Pattern lookForVar;
public PlaceHolderConverter( String placeHolder )
{
this.lookForVar = Pattern.compile( placeHolder );
}
public String format( String text, String... args )
{
if ( args == null || args.length == 0 )
{
return text;
}
StringBuffer stringBuffer = new StringBuffer();
Matcher matcher = lookForVar.matcher( text );
short varCount = 0;
while ( matcher.find() )
{
matcher.appendReplacement( stringBuffer, args[varCount++] );
}
matcher.appendTail( stringBuffer );
return stringBuffer.toString();
}
}
正如您在以下测试中看到的,我对特殊字符美元有疑问,因为它是 java 正则表达式的特殊字符。我试图解决这个问题,Pattern.quote()
但没有结果。
package something;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;
public class PlaceHolderConverterTest
{
private PlaceHolderConverter placeHolderConverter;
@Before
public void before()
{
placeHolderConverter = new PlaceHolderConverter( "\\{\\}" );
}
@Test // SUCCESS
public void whenStringArgsThenReplace()
{
String result = placeHolderConverter.format( "My {} are beautifull", "flowers" );
Assert.assertEquals( "My flowers are beautifull", result );
}
@Test // FAIL IllegalArgumentException illegal group reference while calling appendReplacement
public void assertEscapeDollar()
{
String result = placeHolderConverter.format( "My {} are beautiful", "flow$ers" );
Assert.assertEquals( "My flow$ers are beautiful", result );
}
@Test // FAIL IllegalArgumentException illegal group reference while calling appendReplacement
public void assertEscapeDollarWithQuote()
{
String result = placeHolderConverter.format( "My {} are beautiful", Pattern.quote("flow$ers") );
Assert.assertEquals( "My flow$ers are beautiful", result );
}
}
我还尝试在正则表达式中使用美元之前手动转义美元,.replaceAll("\\$", "\\\\$")
但似乎replaceAll
不喜欢将 arg1 包含在 arg2 中。
我该如何解决?
补丁可以在这里提供https://gist.github.com/3937872