我有一个大文件 (20 mb) 中的 URL 列表,并且有一组关键字。如果关键字集与 url 匹配,那么我想提取该 URL。
示例:关键字=“联系人” 网址:http://www.365media.com/offices-and-contact.html
我需要一个正则表达式来将关键字与我的网址列表进行匹配。
我的Java代码:
public class FileRead {
public static void main(String[] ags) throws FileNotFoundException
{
Scanner in=new Scanner(new File("D:\\Log\\Links.txt"));
String input;
String[] reg=new String[]{".*About.*",".*Available.*",".*Author.*",".*Blog.*",".*Business.*",
".*Career.*",".*category.*",".*City.*",".*Company.*",".*Contain.*",".*Contact.*",".*Download.*",
".*Email.*"};
while(in.hasNext())
{
input=in.nextLine();
//for(String s:reg)
patternFind(input,".*email.*");
}
}
public static void patternFind(String input,String reg)
{
Pattern p=Pattern.compile(reg);
Matcher m=p.matcher(input);
while(m.find())
System.out.println(m.group());
}
}
最佳答案
如果您只想匹配当前行中是否存在任何关键字,您可以简单地使用
for (String s: reg) {
if (input.contains(s)) {
// do something
}
}
而不是 patternFind(input,".电子邮件。");
无论如何,相当于匹配任何单词的正则表达式是:
.*(About|Available|Author|And|So|On...).*
我不确定哪个更快。 String.contains() 更简单,预编译了一个 Pattern,在多次应用时可以表现得更好,就像这里的情况一样。
关于java - URL 中的正则表达式关键字匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11240693/