在字符串中查找一个字符或一组字符并删除它们
Find a character or group of characters in a string and remove them
我正在尝试构建一个程序
- 找到
@
符号,然后
- 找到教育电子邮件地址的
.edu
部分,最后
- 删除
@school.edu
部分,return 其余部分。
我试过使用 charAt
,但我一直收到不兼容类型的错误,而且我不确定如何删除字符串中每次可能位于不同位置的部分。欢迎任何指导。
这是我目前的情况:
if (UserEmail.charAt(0) == (".edu"))
String UserName = UserEmail.substring(0,//location of @//)
else
System.out.print(UserEmail + "is not an acceptable email address.
System.out.print("Type your email address.");
UserEmail = kb.nextLine();
您可以使用 string.replaceAll
函数。
string.replaceAll("@\S+?\.edu\b", "");
\S+?
将对一个或多个非 space 字符进行非贪婪匹配。
示例:
String r = "foo@school.edu bar";
System.out.println(r.replaceAll("@\S+?\.edu\b", ""));
输出:
foo bar
我正在尝试构建一个程序
- 找到
@
符号,然后 - 找到教育电子邮件地址的
.edu
部分,最后 - 删除
@school.edu
部分,return 其余部分。
我试过使用 charAt
,但我一直收到不兼容类型的错误,而且我不确定如何删除字符串中每次可能位于不同位置的部分。欢迎任何指导。
这是我目前的情况:
if (UserEmail.charAt(0) == (".edu"))
String UserName = UserEmail.substring(0,//location of @//)
else
System.out.print(UserEmail + "is not an acceptable email address.
System.out.print("Type your email address.");
UserEmail = kb.nextLine();
您可以使用 string.replaceAll
函数。
string.replaceAll("@\S+?\.edu\b", "");
\S+?
将对一个或多个非 space 字符进行非贪婪匹配。
示例:
String r = "foo@school.edu bar";
System.out.println(r.replaceAll("@\S+?\.edu\b", ""));
输出:
foo bar