Search code examples
javajava-8substringtruncate

Truncate a dynamic value using Java8


In one of my application I used to get some reference number like as shown below

BRD.2323-6984-4532-4444..0
BRD.2323-6984-4532-4445..1
BRD.2323-6984-4532-4446
BRD.2323-6984-4532-4446..5
:
:

How do I truncate the ending ..[n] if it contains in Java like as shown below. If it is a constant number I would have substring it like .substring(0, value.indexOf("..0")), since the number is dynamic should I use Regex?

BRD.2323-6984-4532-4444
BRD.2323-6984-4532-4445
BRD.2323-6984-4532-4446
BRD.2323-6984-4532-4446
:
:

Can someone please help me on this


Solution

  • You could use a regex replacement here:

    String input = "BRD.2323-6984-4532-4444..0";
    String output = input.replaceAll("\\.\\.\\d+$", "");
    System.out.println(input);   // BRD.2323-6984-4532-4444..0
    System.out.println(output);  // BRD.2323-6984-4532-4444
    

    Note that the above replacement won't alter any reference number not having the two trailing dots and digit.