regex - Java―escape string to use in RegExp -


i bit new java, unsure if doing things should or not. developing program, more learning java purpose , thought commandline use. 1 of features should kind of search replace.

starting program commandline this:

java -jar pro.jar -s ${ftp://www.stuff.com} -r foo 

means: search exact string ${ftp://www.stuff.com} , replace foo. want search regexp, have escape escape-characters ($,(,{,},\,…) in search string.

${ftp://www.stuff.com} --> \$\{ftp:\/\/www\.stuff\.com\} 

therefore wrote 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 work, there many backslashes. escape metachrackters? »robust« solution?

you can better use them. can use patternquote.

pattern metas = pattern.quote("no escaped regex chars in here"); 

one other way rid of \\ use character classes []. if put [.] instead of \\. results same , readability.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -