【问题标题】:Perl Regex to match only 1 domainPerl 正则表达式仅匹配 1 个域
【发布时间】:2011-01-12 05:14:17
【问题描述】:

我正在尝试创建一个匹配以下内容的正则表达式:

part1@domain.com

part1:part1 是 0-9 之间的任意 5 位数字
第 2 部分:[可选] 其中@domain.com 是除@yahoo.com 之外的所有域

示例:12345@yahoo.com
我无法找到如何在正则表达式中插入条件。现在只有我的正则表达式匹配数字+域。还需要弄清楚:

  1. 如何只匹配数字
  2. 有条件接受除@yahoo.com 以外的所有域

代码:

#!/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";
  }
}

样本数据:

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

【问题讨论】:

  • 这似乎是一个不使用正则表达式就可以解决的问题。我很好奇你走这条路的原因。(不是说我讨厌正则表达式,或者任何东西看起来就像你在用火箭发射器杀死一只老鼠)

标签: regex perl dns match


【解决方案1】:

为什么不首先检查 yahoo.com,如果找到匹配项,请转到下一行:

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

【讨论】:

    【解决方案2】:

    这个怎么样?

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

    展开形式:

    \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) 就是所谓的“negative lookahead assertion”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多