[英]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
.它代表我的
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.我必须将该
userId
作为参数发送给函数,并以我在第二个@
之后删除数字 5 并附加新数字的方式发送它。
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?使用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:假设您的输入只有两个at 符号,您可以在此处使用正则表达式替换:
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.您可以在第 1 组中捕获要保留的内容,并匹配要删除的内容。
In the replacement use capture group 1 denoted by $1
在替换中使用
$1
表示的捕获组$1
^((?:[^@\s]+@){2}).+
^
Start of string ^
字符串开始(
Capture group 1 (
捕获组 1
(?:[^@\\s]+@){2}
Repeat 2 times matching 1+ chars other than @, and then match the @ (?:[^@\\s]+@){2}
重复2次匹配@以外的1+个字符,然后匹配@)
Close group 1 )
关闭第 1 组.+
Match 1 or more characters that you want to remove .+
匹配 1 个或多个要删除的字符Regex demo |正则表达式演示| Java demo
Java 演示
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:如果字符串也可以以
@@1
开头并且您想保留@@
那么您还可以使用:
^((?:[^@]*@){2}).+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.