0

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

1
  • Or you could simply use .substring(0, value.indexOf("..")), assuming there are no other occurrences of ".." in your input Commented Mar 5, 2021 at 11:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for thee quick reply. Will this takes care if it comes with more than single digit like for example ..10
@AlexMan Yes, it will, try the code out to verify this.
Why replaceAll and not replaceFirst?
@Holger Would you believe it if I told you that I've never used String#replaceFirst? Actually, performance wise it shouldn't matter here, since the regex pattern I used is scoped to only make a replacement at the end of the input. But, you are correct and I agree with your comment.
0

I noticed that one of them, when modified, would result in a duplicate. Here is something that might prove useful using @TimBiegeleisen's answer. It will eliminate duplicates.

List<String> values = List.of(
        "BRD.2323-6984-4532-4444..0",
        "BRD.2323-6984-4532-4445..1",
        "BRD.2323-6984-4532-4446",
        "BRD.2323-6984-4532-4446..5");
UnaryOperator<String> modify = str->str.replaceAll("\\.\\.\\d+$", "");
Set<String> set = values.stream()
        .map(modify::apply)
        .collect(Collectors.toSet());

set.forEach(System.out::println);

Prints

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

1 Comment

There’s no point in writing .map(modify::apply) when you can just write .map(modify).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.