简体   繁体   中英

How to remove everything after specific character in string using Java

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?

Here is a splitting option:

String input = "analitics@gmail.com@5";
String output = String.join("@", input.split("@", 3)) + "@";
System.out.println(output);  // analitics@gmail.com@

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

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

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 = "analitics@gmail.com@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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM