【问题标题】:Perl RegEx to find the portion of the email address before the @Perl Regex在@之前查找电子邮件地址的一部分
【发布时间】:2011-03-21 03:14:59
【问题描述】:

我在 Perl 中有以下问题。我有一个文件,我在其中获取电子邮件列表作为输入。

我想解析所有电子邮件地址的“@”之前的字符串。 (稍后我会将@之前的所有字符串存储在一个数组中)

例如。在:abcdefgh@gmail.com,我想解析电子邮件地址并提取 abcdefgh。

我的意图是只获取'@'之前的字符串。现在的问题是如何使用正则表达式检查它。或者还有其他使用 substr 的方法吗?

虽然我在 Perl 中使用正则表达式:$mail =~ "\@",但它并没有给我结果。

另外,我如何找到字符“@”在字符串 $mail 的哪个索引中?

如果有人可以帮助我,我将不胜感激。

#!usr/bin/perl

$mail = "abcdefgh@gmail.com";

if ($mail =~ "\@" ) {
    print("my name = You got it!");
}
else
{
    print("my name = Try again!");
}

在上面的代码中 $mail =~ "\@" 没有给我想要的输出,但是 ($mail =~ "abc" ) 给了我想要的输出。

$mail =~ "@" 仅在给定字符串 $mail = "abcdefgh\@gmail.com"; 时才有效;

但在我的情况下,我将获得带有电子邮件地址的输入。

不带转义字符。

谢谢,

汤姆

【问题讨论】:

    标签: regex perl email parsing indexing


    【解决方案1】:

    启用警告会指出您的问题:

    #!/usr/bin/perl
    use warnings;
    
    $mail = "abcdefgh@gmail.com";
    __END__
    Possible unintended interpolation of @gmail in string at - line 3.
    Name "main::gmail" used only once: possible typo at - line 3.
    

    启用 strict 甚至会阻止它编译:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $mail = "abcdefgh@gmail.com";
    __END__
    Possible unintended interpolation of @gmail in string at - line 4.
    Global symbol "@gmail" requires explicit package name at - line 4.
    Execution of - aborted due to compilation errors.
    

    换句话说,您的问题不是正则表达式工作或不工作,而是您匹配的字符串包含“abcdefgh.com”,而不是您的预期。

    【讨论】:

      【解决方案2】:

      @ 符号是双引号字符串中的元字符。如果你把你的电子邮件地址放在单引号中,你就不会遇到这个问题。

      另外,我应该添加强制性注释,如果您只是在试验,这很好,但在生产代码中您不应该使用正则表达式解析电子邮件地址,而是使用诸如 Mail::Address 之类的模块。

      【讨论】:

        【解决方案3】:

        如果你尝试这个会怎样:

        my $email = 'user@email.com';
        
        $email =~ /^(.+?)@/;
        print $1
        

        $1 将是 @ 之前的所有内容。

        【讨论】:

          【解决方案4】:

          如果你想要一个字符串的索引,你可以使用index()函数。即。

          my $email = 'foo@bar';
          my $index = index($email, '@');
          

          如果您想返回电子邮件的前半部分,我会使用split() 而不是正则表达式。

          my $email = 'foo@bar';
          my @result = split '@', $email;
          my $username = $result[0];
          

          substr 甚至更好

          my $username = substr($email, 0, index($email, '@'))
          

          【讨论】:

          • 您应该在此代码中使用 rindex 来查找最后一个 @ 而不是第一个。 '@' 在本地部分 ($username) 中有效,根据 rfc2822 作为带引号的字符串的一部分。
          【解决方案5】:
          $mail = 'abcdefgh@gmail.com';
          $mail =~ /^([^@]*)@/;
          print "$1\n"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-03-15
            • 2016-06-01
            • 1970-01-01
            • 2018-02-03
            • 2022-07-14
            • 2015-01-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多