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.
Code
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()
.
Code
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 .