我想执行以下功能:
从给定的段落中提取给定的String,如
String str= "Hello this is paragraph , Ali@yahoo.com . i am entering random email here as this one AHmar@gmail.com " ;
我要做的是解析整个段落,阅读电子邮件地址,并打印他们的服务器名称,我已经使用for
循环substring
方法进行了尝试,确实使用了{{1但是,可能是我的逻辑并不是那么好,有人可以帮我吗?
答案 0 :(得分:3)
在这种情况下,您需要使用正则表达式。
尝试以下正则表达式: -
String str= "Hello this is paragraph , Ali@yahoo.com . i am " +
"entering random email here as this one AHmar@gmail.com " ;
Pattern pattern = Pattern.compile("@(\\S+)\\.\\w+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
输出: -
yahoo
gmail
更新: -
以下是包含substring
和indexOf
的代码: -
String str= "Hello this is paragraph , Ali@yahoo.com . i am " +
"entering random email here as this one AHmar@gmail.com " ;
while (str.contains("@") && str.contains(".")) {
int index1 = str.lastIndexOf("@"); // Get last index of `@`
int index2 = str.indexOf(".", index1); // Get index of first `.` after @
// Substring from index of @ to index of .
String serverName = str.substring(index1 + 1, index2);
System.out.println(serverName);
// Replace string by removing till the last @,
// so as not to consider it next time
str = str.substring(0, index1);
}
答案 1 :(得分:2)
您需要使用正则表达式来提取电子邮件。从this测试工具代码开始。接下来,构建您的正则表达式,您应该能够提取电子邮件地址。
答案 2 :(得分:1)
试试这个: -
String e= "Hello this is paragraph , Ali@yahoo.com . i am entering random email here as this one AHmar@gmail.comm";
e= e.trim();
String[] parts = e.split("\\s+");
for (String e: parts)
{
if(e.indexOf('@') != -1)
{
String temp = e.substring(e.indexOf("@") + 1);
String serverName = temp.substring(0, temp.indexOf("."));
System.out.println(serverName); }}