你的问题写得不好。请改进它。在其当前格式中,它将被关闭为“太模糊”。
您想过滤电子邮件或网站吗?你的例子是关于网站的,你发短信是关于电子邮件的。因为我不知道,我决定无论如何都要帮助你,所以我决定两者都做。
代码如下:
private static final Pattern EMAIL_REGEX =
Pattern.compile("[A-Za-z0-9](:?(:?[_\\.\\-]?[a-zA-Z0-9]+)*)@(:?[A-Za-z0-9]+)(:?(:?[\\.\\-]?[a-zA-Z0-9]+)*)\\.(:?[A-Za-z]{2,})");
private static final Pattern WEBSITE_REGEX =
Pattern.compile("http(:?s?)://[_#\\.\\-/\\?&=a-zA-Z0-9]*");
public static String readFileAsString(String fileName) throws IOException {
File f = new File(fileName);
byte[] b = new byte[(int) f.length()];
InputStream is = null;
try {
is = new FileInputStream(f);
is.read(b);
return new String(b, "UTF-8");
} finally {
if (is != null) is.close();
}
}
public static List<String> filterEmails(String everything) {
List<String> list = new ArrayList<String>(8192);
Matcher m = EMAIL_REGEX.matcher(everything);
while (m.find()) {
list.add(m.group());
}
return list;
}
public static List<String> filterWebsites(String everything) {
List<String> list = new ArrayList<String>(8192);
Matcher m = WEBSITE_REGEX.matcher(everything);
while (m.find()) {
list.add(m.group());
}
return list;
}
为确保它正常工作,首先让我们测试 filterEmails 和 filterWebsites 方法:
public static void main(String[] args) {
System.out.println(filterEmails("Orange, pizza whatever else joe@somewhere.com a lot of text here. Blahblah blah with Luke Skywalker (luke@starwars.com) hfkjdsh fhdsjf jdhf Paulo <aaa.aaa@bgf-ret.com.br>"));
System.out.println(filterWebsites("Orange, pizza whatever else joe@somewhere.com a lot of text here. Blahblah blah with Luke Skywalker (http://luke.starwars.com/force) hfkjdsh fhdsjf jdhf Paulo <https://darth.vader/blackside?sith=true&midclorians> And the http://www.somewhere.com as x."));
}
它输出:
[joe@somewhere.com, luke@starwars.com, aaa.aaa@bgf-ret.com.br]
[http://luke.starwars.com/force, https://darth.vader/blackside?sith=true&midclorians, http://www.somewhere.com]
要测试 readFileAsString 方法:
public static void main(String[] args) {
System.out.println(readFileAsString("C:\\The_Path_To_Your_File\\SomeFile.txt"));
}
如果该文件存在,将打印其内容。
如果您不喜欢它返回List<String>
而不是String
用空格分隔的项目,这很容易解决:
public static String collapse(List<String> list) {
StringBuilder sb = new StringBuilder(50 * list.size());
for (String s : list) {
sb.append(" ").append(s);
}
sb.delete(0, 1);
return sb.toString();
}
粘在一起:
String fileName = ...;
String webSites = collapse(filterWebsites(readFileAsString(fileName)));
String emails = collapse(filterEmails(readFileAsString(fileName)));