當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Perl grep()用法及代碼示例

Perl中的grep()函數用於從給定的數組中提取任何元素,該元素為給定的正則表達式求值。

用法: grep(Expression, @Array)

參數:


  • Expression :它是用於在給定數組的每個元素上運行的正則表達式。
  • @Array:這是在其上調用grep()函數的給定數組。

返回值:給定數組中為給定正則表達式求真值的任何元素。

示例1:

#!/usr/bin/perl 
  
# Initialising an array of some elements 
@Array = ('Geeks', 'for', 'Geek'); 
  
# Calling the grep() function 
@A = grep(/^G/, @Array); 
  
# Printing the required elements of the array 
print @A;


輸出:

GeeksGeek

在上麵的代碼中,正則表達式/^G /用於從給定數組中獲取以“ G”開頭的元素,並丟棄其餘元素。

示例2:

#!/usr/bin/perl 
  
# Initialising an array of some elements 
@Array = ('Geeks', 1, 2, 'Geek', 3, 'For'); 
  
# Calling the grep() function 
@A = grep(/\d/, @Array); 
  
# Printing the required elements of the array 
print @A;

輸出:

123

在上麵的代碼中,正則表達式/^d /用於從給定數組中獲取整數值並丟棄其餘元素。

示例3:

#!/usr/bin/perl 
  
# Initialising an array of some elements 
@Array = ('Ram', 'Shyam', 'Rahim', 'Geeta', 'Sheeta'); 
  
# Calling the grep() function 
@A = grep(!/^R/, @Array); 
  
# Printing the required elements of the array 
print @A;

輸出:

ShyamGeetaSheeta

在上麵的代碼中,正則表達式!/^R /用於獲取不是以'R'開頭的元素,並丟棄以'R'開頭的元素。



相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Perl | grep() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。