javascript - regex - javascript匹配不包含字符的字符串

我正在尝试使用javascript匹配包含一个目录的url模式,并带有一个可选的尾部斜杠。

以下是我到目前为止尝试过的内容:

方法是匹配url,然后使用否定字符类或否定回溯,

我尝试了以下方法:


/(https?:)?(//)?(www.)?twitter.com/[a-z0-9_+-]+/?(?![a-z0-9_+-])/ig




/(https?:)?(//)?(www.)?twitter.com/w+[^/w]*/ig



我尝试过这样的变种,但是无法使它工作:


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));

时间:


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));

我使用正前导来断言在最后一组后面有一个空白字符或字符串的结尾。

(?:https?://)?(?:www.)?twitter.com/w+(?=s|$)

尝试一下正则表达式。


var regex1 = /(https?:)?(//)?(www.)?twitter.com/([wd_-]+/?)$/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));

...