javascript Reg Exp匹配特定的域名

javascript Reg Exp to match specific domain name

本文关键字:域名 Reg Exp javascript      更新时间:2023-09-26

我一直在尝试使Reg Exp与特定域名的URL匹配。

如果我想检查这个url是否来自example.com什么regexp应该是最好的?

这个正则表达式应该匹配以下类型的url:

http://api.example.com/...
http://preview.example.com/...
http://www.example.com/...
http://purhcase.example.com/...

只是简单的规则,像http://{something}.example.com/{something}那样应该通过。

谢谢。

我想这就是你要找的:(https?:'/'/(.+?'.)?example'.com('/[A-Za-z0-9'-'._~:'/'?#'[']@!$&''(')'*'+,;'=]*)?)

分解如下:

  • https?:'/'/匹配http://https://(你没有提到https,但这似乎是个好主意)。
  • (.+?'.)?匹配第一个点之前的任何内容(我将其设置为可选的,因此,例如,http://example.com/将被发现
  • example'.com(当然是example.com);
  • ('/[A-Za-z0-9'-'._~:'/'?#'[']@!$&''(')'*'+,;'=]*)?):一个斜杠后面跟着URL中所有可接受的字符;我将此设置为可选,以便找到http://example.com(没有最后的斜杠)。

示例:https://regex101.com/r/kT8lP2/1

使用indexOf javascript API。:)

var url = 'http://api.example.com/api/url';
var testUrl = 'example.com';
if(url.indexOf(testUrl) !== -1) {
    console.log('URL passed the test');
} else{
    console.log('URL failed the test');
}
编辑:

为什么用indexOf代替Regular Expression

你看,你在这里匹配的是一个简单的字符串(example.com)而不是pattern。如果你有一个固定的字符串,那么不需要通过检查模式来引入语义复杂性。

正则表达式最适合用于确定模式是否匹配。

例如,如果您的要求是域名应该以ex开始,以le结束,并且在开始和结束之间,它应该包含字母数字字符,其中必须有4个字符是大写的。在这种情况下,正则表达式将被证明是有用的。

你的问题很简单,所以没有必要雇佣1000个天使来说服一个爱你的人。div;)

使用

/^[a-zA-Z0-9_.+-]+@(?:(?:[a-zA-Z0-9-]+'.)?[a-zA-Z]+'.)?
(domain|domain2)'.com$/g

匹配您选择的特定域。

如果您只想匹配一个域,那么从(domain|domain2)部分中删除|domain2

它会帮助你。https://www.regextester.com/94044

不确定这是否适合您的情况,但是依赖内置的URL解析器可能比使用正则表达式更好。

var url  = document.createElement('a');
url.href = "http://www.example.com/thing";

然后你可以使用API

给出的方法调用这些值
url.protocol // (http:)
url.host     // (www.example.com)
url.pathname // (/thing)

如果这对你没有帮助,像这样的东西可以工作,但可能太脆弱:

var url     = "http://www.example.com/thing";
var matches = url.match(/:'/'/(.[^'/]+)(.*)/);
// matches would return something like
// ["://example.com/thing", "example.com", "/thing"]

这些帖子也可能有所帮助:

https://stackoverflow.com/a/3213643/4954530

https://stackoverflow.com/a/6168370

祝你好运!

在某些情况下,您正在寻找的域名实际上可以在查询部分找到,而不是在域名部分:https://www.google.com/q=www.example.com

这个答案会更好地处理这种情况。
参见regex101中的这个例子。

正如你所指出的,你只需要example.com(写域名然后转义句号然后com),所以在regex中使用它。

例子

更新

请看下面的答案