The regular expression you're trying is perfect.
The problem is in the replacement text. You have to escape the
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
Additionally, if you would like to make sure that any replacement text is taken literally, you can use the method
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);
Why do you have to escape each bar with 4 bars?
In Java, a bar
\ serves as character escape sequence
\t , etc. Therefore, a literal bar must be
"\" . 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
( 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 .