Replace a route with regex. Error: "character to be escaped is missing"


I have a program that detects every time a new file is created, and I want to copy that file to a new location.

My problem is that I do not know how to do to remove the piece C:\Archive and delete it for the new location.

ruta = ruta.replaceFirst("C:\\Archive\\*", "E:\");

I'm trying this, but it gives me an error:

java.lang.IllegalArgumentException: character to be escaped is missing

I try, for example, the texts:


Replaced by:


Any help? Thanks.

asked by pitiklan 22.02.2017 в 20:11

1 answer


The regular expression you're trying is perfect.

The problem is in the replacement text. You have to escape the \ .


In String.replaceFirst() is mentioned:


Please note that the bars ( \ ) and the signs weights ( $ ) in the replacement text may cause the results to be different from what a literal text would be.


ruta = ruta.replaceFirst("^C:\\Archive(?:\\+|$)", "E:\\");
//            escapado con 4 barras por cada una literal ^^^^

I also modified some details:

  • I added ^ to match only the beginning of the text.
  • Modified the end of the regex so that it does not match C:\Archivero2

Demo: link

Additionally, if you would like to make sure that any replacement text is taken literally, you can use the method Matcher.quoteReplacement() .


import java.util.regex.Matcher;
String ruta  = "C:\Archive\carpeta\archivo.ej";
String regex = "^C:\\Archive(?:\\+|$)";
String reemp = "E:\";
System.out.println("Ruta: " + ruta);

ruta = ruta.replaceFirst(regex, Matcher.quoteReplacement(reemp));
//escapar caracteres especiales ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
System.out.println("Reemplazada: " + ruta);

Demo: link


Why do you have to escape each bar with 4 bars?


In Java, a bar \ serves as character escape sequence   literal as \n . \t , etc. Therefore, a literal bar must be   write as "\" . That is, they are 2 bars for every 1 literal.


Also, the bar also works as an escape for regex!   Mainly, it serves to escape the $ that otherwise   They would have a special meaning. For example, it would be used if we capture   text in parentheses and we use it in the replacement as $1   ( demo ). But to replace with a literal $ sign, it should be   escape with a bar as \$ ( demo ).


Then, for each bar in the replacement text:

  • There are 2 bars for Java to interpret as an escape sequence.
  • There are 2 bars for regex to take as literal.
  • 4 bars in total .
answered by 23.02.2017 / 05:15