-1

Looking for some help to find how to replace the last "." char to some other string via regex in java. I have code something like this which doesn't work. Any advise.

"//myserver.com//NAGA.CSV".replaceAll(".$","_2.")

Output: //myserver.com//NAGA_2.CSV

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
Naga
  • 444
  • 2
  • 7
  • 18

2 Answers2

3

You could use a lookahead, to find the end of the string, preceded by characters other than dot.

yourString.replaceAll("\\.(?=[^.]*$)", "replacement");

Note that the first dot needs to be escaped with a backslash, because dot has a special meaning in a regular expression (it matches any character). The second dot doesn't need to be escaped, because the special meaning doesn't apply in square brackets.

The (?= ) structure means "followed by this" - in other words, the dot that you match can be followed by any number of non-dot characters, and then the end of the string. Those extra characters are not considered part of the match.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

It's not a regex, but you could use the String.lastIndexOf() method to get the position of the last occurence of your char and use String.substring to create your new String:

String yourString = "test.csv";
String newValue = "_2.";
int lastOccurence = yourString.lastIndexOf(".");
String replacedString = yourString.substring(0, lastOccurence) + newValue + yourString.substring(lastOccurence + 1);
Christian
  • 22,585
  • 9
  • 80
  • 106