我正在尝试使用 Javascript 匹配包含一个目录的 url 模式,并带有可选的尾部斜杠。
例如
这应该匹配:
text and http://twitter.com/path and more text
这不应该匹配:
text and http://twitter.com/path/other/directories and more text
即使较短的字符串存在于较长的字符串中,我也不希望较长的字符串返回任何内容。
这可能吗?
<小时/>这是我迄今为止尝试过的:
方法是匹配 url,然后使用否定字符类或否定回溯
我尝试过以下方法:
/(https?:)?(\/\/)?(www\.)?twitter\.com\/[a-z0-9_+-]+\/?(?![a-z0-9_+-])/ig
这是为了查找 Twitter URL,带有 \w+
路径,带有可选的尾部斜杠,后面不跟任何其他 \w+
。
虽然这不包括其匹配中的第二个目录,但我希望它根本不匹配该字符串。
/(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 = 'text https://twitter.com/page text';
var shouldNotMatch = 'text https://twitter.com/page/status/123 text';
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));
最佳答案
您可以在有效部分末尾使用否定前瞻,断言页面名称后面没有 /
和单词字符或另一个单词字符。在否定前瞻中添加其他单词字符替换可以防止正则表达式在(例如)http://twitter.com/pag
处匹配。
var regex1 = /(https?:\/\/)?(www\.)?twitter\.com\/\w+(?!\/\w|\w)/ig;
var shouldMatch = 'https://twitter.com/page is a valid url';
var shouldNotMatch = 'https://twitter.com/page/status/123 is not valid';
console.log('regex1 should match', shouldMatch.match(regex1));
console.log('regex1 should return []', shouldNotMatch.match(regex1));
关于Javascript 匹配不包含字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59241571/