gpt4 book ai didi

java - 从段落中提取给定的子字符串

转载 作者:行者123 更新时间:2023-11-30 05:51:12 27 4
gpt4 key购买 nike

我想执行以下功能:

从给定的段落中提取给定的字符串,例如

String str= "Hello this is paragraph , Ali@yahoo.com . i am entering  random  email here as this one  AHmar@gmail.com " ; 

我要做的是解析整个段落,读取电子邮件地址,并打印他们的服务器名称,我已经尝试使用 for 循环和 substring 方法, 确实使用了 indexOf ,但可能是我的逻辑不太好理解,有人可以帮我吗?

最佳答案

对于这种情况,您需要使用正则表达式。

试试下面的正则表达式:-

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

更新:-

这是带有 substringindexOf 的代码:-

   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);

}

关于java - 从段落中提取给定的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13038711/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com