Home > database >  How to remove everything after specific character in string using Java
How to remove everything after specific character in string using Java

Time:11-03

I have a string that looks like this:

analitics@gmail.com@5

And it represents my userId.

I have to send that userId as parameter to the function and send it in the way that I remove number 5 after second @ and append new number.

I started with something like this:

userService.getUser(user.userId.substring(0, userAfterMigration.userId.indexOf("@")   1)   3

What is the best way of removing everything that comes after the second @ character in string above using Java?

CodePudding user response:

Here is a splitting option:

String input = "[email protected]@5";
String output = String.join("@", input.split("@")[0], input.split("@")[1])   "@";
System.out.println(output);  // [email protected]@

Assuming your input would only have two at symbols, you could use a regex replacement here:

String input = "[email protected]@5";
String output = input.replaceAll("@[^@]*$", "@");
System.out.println(output);  // [email protected]@

CodePudding user response:

You can capture in group 1 what you want to keep, and match what comes after it to be removed.

In the replacement use capture group 1 denoted by $1

^((?:[^@\s] @){2}). 
  • ^ Start of string
  • ( Capture group 1
    • (?:[^@\s] @){2} Repeat 2 times matching 1 chars other than @, and then match the @
  • ) Close group 1
  • . Match 1 or more characters that you want to remove

Regex demo | Java demo

String s = "[email protected]@5";
System.out.println(s.replaceAll("^((?:[^@\\s] @){2}). ", "$1"));

Output

analitics@gmail.com@

If the string can also start with @@1 and you want to keep @@ then you might also use:

^((?:[^@]*@){2}). 

Regex demo

CodePudding user response:

The simplest way that would seem to work for you:

str = str.replaceAll("@[^.]*$", "");

See live demo.

This matches (and replaces with blank to delete) @ and any non-dot chars to the end.

  • Related