Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何忽略除symbol“以外的所有域后区域”/&引用;_Regex_String_Perl_Pcre - Fatal编程技术网

Regex 如何忽略除symbol“以外的所有域后区域”/&引用;

Regex 如何忽略除symbol“以外的所有域后区域”/&引用;,regex,string,perl,pcre,Regex,String,Perl,Pcre,我有用户名为的匹配域的正则表达式: /(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:facebook)\.com\/(\w+(?:\.\w+)*)$/ 此正则表达式匹配示例URL: facebook.com/username www.facebook.com/username http://facebook.com/username http://www.facebook.com/username https://facebook.com/username

我有用户名为的匹配域的正则表达式:

/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:facebook)\.com\/(\w+(?:\.\w+)*)$/
此正则表达式匹配示例URL:

facebook.com/username
www.facebook.com/username
http://facebook.com/username
http://www.facebook.com/username
https://facebook.com/username
https://www.facebook.com/username
如何为具有域区域和非必需符号的仅匹配URL更改此正则表达式
/

facebook.com
facebook.com/
.....................
https://facebook.com/
https://www.facebook.com

您只想匹配仅包含域的字符串,然后可以使用如下内容:

^(?:https?:\/\/)?(?:www\.)?facebook\.com\/?$
无论它是否有协议(
http(s):\/\/
),也不管它是否包含
www.
,这都将匹配

分解正则表达式,
^(?:https?:\/\/)(?:www\)?facebook\.com\/?$

  • ^
    字符串的开头
  • (?:https?:\/\/)?
    与协议
    https?:\/\/
    匹配的非捕获组,零次或一次
    (可选)
  • (?:www\)?
    将在
    www.
    上匹配的非捕获组,零次或一次
    (可选)
  • facebook\.com
    将匹配该域
  • \/?
    将匹配可选的
    正斜杠
    \/
  • $
    字符串结尾(添加了强调)-这是允许它与您的需求一起工作的原因,因为这将不允许在前面的项目符号中的可选正斜杠之后有任何匹配

由于这是标记为Perl的,Perl的答案是使用URI解析模块,如或

使用严格;
使用警告;
使用Mojo::URL;
while(my$input=){#或以任何方式输入
chomp$输入;
我的$url=Mojo::url->new($input);
下一步除非!定义了$url->scheme或$url->scheme eq'http'或$url->scheme eq'https';
下一步,除非定义了$url->host和($url->host eq'facebook.com'或$url->host eq'www.facebook.com');
下一步如果长度为$url->path和$url->path ne'/';
打印“$input\n”;
}

所以您希望匹配只有域的字符串,并且在末尾没有正斜杠?@K.Dᴀᴠɪs唯一一个有或没有slash的域名可以更清楚地显示上面6个URL中的哪一个应该匹配,然后解释为什么会这样?这是Perl还是PCRE?您已经标记了两者,但它们是不同的东西如果我理解正确,这应该可以工作
^(?https?:\/\/)?(?:www\)?facebook\.com\/?$
use strict;
use warnings;
use Mojo::URL;
while (my $input = <<>>) { # or whatever way the input comes in
  chomp $input;
  my $url = Mojo::URL->new($input);
  next unless !defined $url->scheme or $url->scheme eq 'http' or $url->scheme eq 'https';
  next unless defined $url->host and ($url->host eq 'facebook.com' or $url->host eq 'www.facebook.com');
  next if length $url->path and $url->path ne '/';
  print "$input\n";
}