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

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -