Javascript 匹配不包含字符的字符串

标签 javascript regex

我正在尝试使用 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/

相关文章:

容器 div 内的 JavaScript div 不会执行某些代码

php - 审查可能包含标记的不当词语的最佳方法是什么?

C++11 正则表达式抛出 std::regex_error

正则表达式 - 忽略具有匹配文本的行

python - 使用区分大小写和不区分大小写的混合模式的正则表达式查找文本中使用的人称代词的数量

javascript - 如何使用 Zapier 获取 JSON 数组中的第一个值?

javascript - 如何让两个 Controller 在 Angular 中执行相同的操作,但改变网站的视觉方面?

javascript - Colspan 属性未从变量设置

Javascript .load 看不到 PHP 的变量

java - 我收到 "unreported exception ioexception; must be kept or declared to be thrown"