1

Apify PseudoUrl支持 JavaScript 样式的正则表达式来匹配 URL。

我尝试按照 RegEx 匹配包含特定关键字的所有 url -

//not working
http://www.example.com/[*foo*]

例如,如果一个网站有以下链接:

http://www.example.com/pages/
http://www.example.com/pages/bar

http://www.example.com/pages/foo/bar.html
http://www.example.com/pages/test-foo-test.html
http://www.example.com/pages/foo.html

正则表达式应匹配最后 3 个网址。但是,正则表达式不起作用。

4

2 回答 2

2

您需要检查foo域内容之后是否存在任何位置:

http:\/\/www\.example\.com\/.*foo

https://regex101.com/r/UlSb4w/2

于 2019-08-23T16:42:09.567 回答
2

您还将常规 javascript 正则表达式传递给PseudoUrl构造函数。

你会想要一个形式的正则表达式^http:\/\/www.example.com\/pages\/.*foo

假设您想对多个关键字执行此操作,您可以使用如下内容:

const Apify = require('apify');
const regexEscape = require('regex-escape');

function createKeywordUrlRegex(baseUrl, keyword) {
  const regexStr = `^${regexEscape(baseUrl)}.*?${regexEscape(keyword)}`;
  // remove the i if you want to match to be case-sensitive
  return new RegExp(regexStr, 'i');
}

const purl = new Apify.PseudoUrl(createKeywordUrlRegex('http://www.example.com/pages/', 'foo'));

// print out the examples
const examples = [
'http://www.example.com/pages/',
'http://www.example.com/pages/bar',
'http://www.example.com/pages/foo/bar.html',
'http://www.example.com/pages/test-foo-test.html',
'http://www.example.com/pages/foo.html'
];
for(let example of examples)
  console.log(example, purl.matches(example) ? 'MATCH!' : 'IGNORED');

您可以传递一个 base url likehttp://www.example.com/pages/和一个关键字 like footo createKeywordUrlRegex,它会为您生成上面提到的正则表达式。

于 2019-08-23T16:50:06.050 回答