我有一个大文件(20MB)的URL列表,我有一组关键字。如果关键字集与URL匹配,那么我想提取url。
Example:keyword=“联系方式”网址:http://www.365media.com/offices-and-contact.html
我需要一个正则表达式来匹配关键字与我的URL列表。
我的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());
}
}
发布于 2012-06-28 16:31:41
为什么你不能这样做:
For all line (URLs) in the file check if some of your pattern works on the URL
代码是非常明显的
发布于 2012-06-28 16:40:52
我将给出一个通用的解决方案。我认为你应该能够将这个想法应用到你的代码中。
假设您在文件中有一个空关键字列表,并将其读取到String[]
中,或者在String[]
中硬编码关键字列表,例如:
String keywords[] = {"about", "available", "email"};
对于所有关键字,使用Pattern.quote()
确保它们被识别为文字字符串。然后用条形字符|
作为分隔符(OR)连接关键字,并用括号()
将所有关键字括起来。最终结果将是这样的。或者,您可以自己查看关键字,然后编写不带引号\Q
和\E
的正则表达式。如果您确定关键字不包含正则表达式,也可以忽略Pattern.quote()
步骤。
(\Qabout\E|\Qavailable\E|\Qemail\E)
将.*
添加到2个末尾,使其与URL的其余部分匹配,并在开头添加(?i)
,以启用不区分大小写的匹配。
(?i).*(\Qabout\E|\Qavailable\E|\Qemail\E).*
然后,您可以编译Pattern
并在每一行输入上调用matcher(inputString).matches()
,以检查该URL是否包含该关键字。
如果关键字在URL中太常见,例如"com“、"net”、"www",而您想要使搜索更细粒度,则必须进行更多的调整。
https://stackoverflow.com/questions/11240693
复制相似问题