我正在尝试使用Javascript匹配一个包含一个目录的URL模式,并带有可选的斜杠。
例如
这应该匹配:
这不应该匹配:
http://twitter.com/path //其他/目录
即使较短的字符串存在于较长的字符串中,我也不希望较长的字符串返回任何内容。
这可能吗?
这是到目前为止我尝试过的:
方法是匹配URL,然后使用否定字符类或否定回溯
我尝试了以下操作:
/(https?:)?(\/\/)?(www\.)?twitter\.com\/[a-z0-9_+-]+\/?(?![a-z0-9_+-])/ig
这是要查找具有\w+
路径,带有可选的斜杠,而不是其他\w+
的Twitter URL。
尽管此目录不包含第二个目录,但我希望它根本不匹配字符串。
/(https?:)?(\/\/)?(www\.)?twitter\.com\/\w+[^\/\w]*/ig
这是为了找到URL,但不包括斜杠和\w
。与以前的尝试类似,它仍然与长链接匹配。
我已经尝试过类似的变体,但无法使其正常工作:
var regex1 = /(https?:)?(\/\/)?(www\.)?twitter\.com\/\w+(?!\/\w+)/ig;
var regex2 = /(https?:)?(\/\/)?(www\.)?twitter\.com\/\w+[^\/\w]*/ig;
var shouldMatch = 'https://twitter.com/page';
var shouldNotMatch = 'https://twitter.com/page/status/123';
console.log('regex1 should match', shouldMatch.match(regex1));
console.log('regex1 should return []', shouldNotMatch.match(regex1));
console.log('regex2 should match', shouldMatch.match(regex2));
console.log('regex2 should return []', shouldNotMatch.match(regex2));
尝试使用正则表达式。
var regex1 = /(https?:)?(\/\/)?(www\.)?twitter\.com\/\w+$/ig;
var shouldMatch = 'https://twitter.com/page';
var shouldNotMatch = 'https://twitter.com/page/status/123';
console.log('regex1 should match', shouldMatch.match(regex1));
console.log('regex1 should return []', shouldNotMatch.match(regex1));