I am a bit new to Java, so I am just unsure if I am doing things like they should or not. I am developing a Program, that is more for learning Java purpose and which is thought for commandline use. One of the Features should be a kind of search an replace.
Starting the program from the commandline like this:
java -jar pro.jar -s ${ftp://www.stuff.com} -r foo
means: search for the exact String ${ftp://www.stuff.com} and replace it with foo. I want to search with an Regexp, so I have to escape the escape-characters ($,(,{,},\,…) in the search string.
${ftp://www.stuff.com} --> \$\{ftp:\/\/www\.stuff\.com\}
Therefore I wrote that function:
private static Pattern getSearchPattern()
{
String searchArg = cli.getOptionValue( "s" ).trim();
StringBuffer escapedSearch = new StringBuffer();
Pattern metas = Pattern.compile( "([\\.\\?\\*\\{\\}\\[\\]\\(\\)\\^\\$\\+\\|\\\\])" );
Matcher metaMatcher = metas.matcher( searchArg );
while( metaMatcher.find() )
{
metaMatcher.appendReplacement(escapedSearch, "\\\\\\\\$0" );
}
metaMatcher.appendTail( escapedSearch );
return Pattern.compile( escapedSearch.toString() );
}
all in all does this work, but there are so many backslashes. Does this escape all metachrackters? Is that a »robust« solution?