Perl Regex中的分组和交替法

Perl Regex中的分组和交替法

Regex或正则表达式Perl 编程的一个重要部分。它用于搜索指定的文本模式。在这里,一组字符共同构成了搜索模式。它也被称为 _ regexp。_ 随着功能的不断增加,使用 regex 可能会变得复杂。为了减少这种复杂性,Perl为我们提供了更多的操作,如交替和分组。

交替运算

这个名字本身就说明了它的作用,首先,它就像C语言中的(&&)运算符。C语言中的’&&’运算符的工作原理是,在发现所有的条件语句都是真的时候,它不会返回1,而一旦发现有错误的语句,它就会返回0。Perl中的交替运算以两种方式同时工作。交替可以用元字符’|’或'[]’来完成。下面的例子可以说明问题:

例1:

#!/usr/bin/perl
 
# Initializing the string and checking it
# against few search patterns
my str = "geeksforgeeks rocks...";
 
# prints 1 due to no match (=0)
print "1\n" if ((str =~ /gek|for/) == 0);
 
# for word search
if(str =~ /geek|for/)
{
    print "I found&.\n";
}
else
{
    print "no match"
}

输出

1
I found geek.

因此,在上面的例子中,它首先检查’geek’,并在第一个备用模式中找到匹配,一旦找到匹配,就返回1。但是它也会检查’for’,如果它不在字符串中出现,它就不会被打扰,因为它已经返回了匹配状态。如果’for’是一个匹配项,它会检查’for’是否出现在字符串的最小位置,因为’geek’中的’g’出现在第0位,’for’中的’f’出现在第5位,’geek’被保存在最后一个匹配模式中。请看下面的例子:

 **$ &** - Contains the string matched by the last pattern match.

例2:

#!/usr/bin/perl
 
# Initializing the string and checking it
# against few search patterns
my str = "geeksforgeeks rocks...";
print "1\n" if (str =~ /for|eeks|rock|ge/);
 
# | for word search
if(str =~ /for|eeks|rock|ge/)
{
    print "I found&.\n";
}
 
# for single character search
if (str =~ /[gfrkc]/)
{
    print "&"
}

输出

1
I found ge.
g

分组

分组是用来搜索一个与相似的词或模式相联系的模式,在开始、结束或中间,它也会返回位置最小的模式。分组是使用元字符'()’完成的。以下是一个例子,它将使事情变得清晰:

例子1:

#!/usr/bin/perl
# Initializing the string and checking it
# against few search patterns
my str = "Blackbackground Brownbackground";
print "1\n" if (str =~ /(Bron|Back)[a-z]+/);
if (str =~ /(Brown|Black)[a-z]+/)
{
    print "I found&.\n";
}
 
else
{
    print "no match"
}

输出

I found Blackbackground.

为了更好地理解,请看下面的例子:

#!/usr/bin/perl
use warnings;
use strict;
 
# Initializing the string and checking it
# against few searching patterns
 
# array of strings
my @mail = ('Ab-@gmail.com',
            'd.f@yahoo.com',
            '0b_f@bing.com',
            'jet@hotmail.con',
            's/s@otmail.com');
 
for(@mail)
{
    # search pattern to check valid mail
    # service providers followed with '.com'
    print "Valid : _\n"
    if(_ =~ /[a-zA-Z0-9-._]+@(gmail|yahoo|bing|hotmail)(.com)$/)
}

输出

Valid : Ab-@gmail.com
Valid : d.f@yahoo.com
Valid : 0b_f@bing.com

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程