我正在尝试找到合适的正则表达式来解析 robots.txt 文件。
所以我正在做的是将页面放入一个字符串中,例如:
User-agent: *
Disallow: /a
Disallow: /b/c
Disallow: /d/c/h
User-agent: agent1
Disallow: /a1/c1
Disallow: /b1/d1
User-agent: agent2
Disallow: /a2/c2
Disallow: /b2/d2
所以我想做的是创建一个正则表达式来为每个用户代理获取代理名称(*,agent1,agent2)及其禁止列表。
这是我尝试过的代码,但没有得到我期望的结果:
public void parseRobotsTxt() {
String website = "http://http://www.EXAMPLE.com";
String content = PageUtils.getStringSource(website + "/robots.txt");
Pattern pattern = Pattern.compile(".*?User-agent:(.*?)(Disallow:(.*?))",Pattern.DOTALL);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
System.out.println("The user agent:" + matcher.group(1));
System.out.println("Disallow List: ");
System.out.println("The user agent:" + matcher.group(2));
System.out.println("----------------------");
}
}
不幸的是我得到的结果是
The user agent: *
Disallow List:
Disallow:
----------------------
The user agent: agent1
Disallow List:
Disallow:
----------------------
The user agent: agent2
Disallow List:
Disallow:
----------------------
我得到了代理名称,但没有得到禁止列表。
最佳答案
如果我正确理解您的问题,您想要捕获用户代理名称及其禁止列表。
为此,我可以想出一个简单的正则表达式,如下所示:
User-agent: (.*)|Disallow: (.*)
<强> Working demo
这个想法是在组 1 中捕获代理名称,在组 2 中捕获禁止列表。这里有比赛信息
Match 1 Group 1. 12-13 `*`
Match 2 Group 2. 24-26 `/a`
Match 3 Group 2. 37-41 `/b/c`
Match 4 Group 2. 52-58 `/d/c/h`
Match 5 Group 1. 72-78 `agent1`
Match 6 Group 2. 89-95 `/a1/c1`
Match 7 Group 2. 106-112 `/b1/d1`
Match 8 Group 1. 126-132 `agent2`
Match 9 Group 2. 143-149 `/a2/c2`
Match 10 Group 2. 160-166 `/b2/d2`
关于Java正则表达式解析/robots.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42650179/