Perl |正则表达式

正则表达式(Regex或Regexp或RE) 在Perl中,是一个特殊的文本字符串,用于描述给定文本中的搜索模式。Perl中的正则表达式链接到宿主语言,与PHP、Python等中的正则表达式不同。有时它被称为 “Perl 5兼容正则表达式” .要使用正则表达式,绑定运算符 ‘=~‘ (Regex操作员)和 ‘!~‘ 使用(否定正则表达式运算符)。在转到绑定操作符之前,让我们先看看构建模式。

null

建筑模式: 在Perl中,可以使用 m// 操作人员在这个操作符中,所需的模式被简单地放在两个斜杠之间,绑定操作符用于搜索指定字符串中的模式。

使用m//和绑定运算符: 大多数绑定运算符与 m// 操作员,以便匹配所需的图案。正则表达式运算符用于将字符串与正则表达式匹配。语句的左侧将包含一个字符串,该字符串将与包含指定模式的右侧匹配。否定正则表达式运算符用于检查字符串是否不等于右侧指定的正则表达式。

  • 项目1: 下面来说明’m/’和’=~’的用法:

    # Perl program to demonstrate
    # the m// and =~ operators
    # Actual String
    $a = "GEEKSFORGEEKS" ;
    # Prints match found if
    # its found in $a
    if ( $a =~ m[GEEKS])
    {
    print "Match Found" ;
    }
    # Prints match not found
    # if its not found in $a
    else
    {
    print "Match Not Found" ;
    }

    
    

    输出:

    Match Found
    

  • 项目2: 来说明“m/”和“!~”的用法详情如下:

    # Perl program to demonstrate
    # the m// and !~ operators
    # Actual String
    $a = "GEEKSFORGEEKS" ;
    # Prints match found if
    # its not found in $a
    if ( $a !~ m[GEEKS])
    {
    print "Match Found" ;
    }
    # Prints match not found
    # if it is found in $a
    else
    {
    print "Match Not Found" ;
    }

    
    

    输出:

    Match Not Found
    

正则表达式的用法:

  • 它可以用来计算字符串中指定模式的出现次数。
  • 它可以用来搜索与指定模式匹配的字符串。
  • 它还可以用其他指定的字符串替换搜索的模式。
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享