简体   繁体   English

Perl Regex只匹配1个域名

[英]Perl Regex to match only 1 domain

I'm trying to create a regex which matches the following: 我正在尝试创建一个匹配以下内容的正则表达式:

part1@domain.com part1@domain.com

part1: where part1 is any 5 digit number from 0-9 第1部分:其中part1是0-9之间的任何5位数字
part2: [optional] where @domain.com are all domains except @yahoo.com 第2部分:[可选]其中@ domain.com是除@ yahoo.com之外的所有域名

example: 12345@yahoo.com 例如: 12345@yahoo.com
I'm not able to find how to insert a conditional into the regex. 我无法找到如何在正则表达式中插入条件。 Now only my regex match digits + domain. 现在只有我的正则表达式匹配数字+域。 Still need to figure out: 仍需要弄清楚:

  1. how to match only the digits 如何只匹配数字
  2. conditional to accept all domains except @yahoo.com 有条件接受除@ yahoo.com以外的所有域名

Code: 码:

#!/usr/bin/perl
use strict;
use warnings;

my $regex1 = '^(\d{5})([@]([a-zA-Z0-9_-]+?\.[a-zA-Z]{2,6})+?)';

while ( my $line = <DATA> ) {
  chomp $line;
  if ($line =~ /$regex1/)
  {
    print "MATCH FOR:\t$line \n";
  }
}

Sample data: 样本数据:

1234
12345@
12345@tandberg
A12345@tandberg.com
12345
12345@tandberg.com
12345@cisco.com
12345@tandberg.amer.com
12345@tandberg.demo

why not simply first check for yahoo.com and if you get a match go to the next line: 为什么不首先检查yahoo.com,如果你得到一个匹配,请转到下一行:

while ( my $line = <DATA> ) {
  chomp $line;
  next if ($line =~ /yahoo\.com$/);
  if ($line =~ /$regex1/)
  {
    print "MATCH FOR:\t$line \n";
  }
}

How about this? 这个怎么样?

\d{5}(?:@(?!yahoo)[a-zA-Z0-9.]+\.[a-zA-Z]{2,3})?

In expanded form: 以扩展形式:

\d{5}            # 5 digits
(?:              # begin a grouping
  @              # literal @ symbol
  (?!yahoo\.com) # don't allow something that matches 'yahoo.com' to match here
  [a-zA-Z0-9.]+  # one or more alphanumerics and periods
  \.             # a literal period
  [a-zA-Z]{2,3}  # 2-3 letters
)                # end grouping
?                # make the previous item (the group) optional

(?!yahoo\\.com) is what's called a " negative lookahead assertion ". (?!yahoo\\.com)被称为“ 负前瞻断言 ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM