Recent Posts
Recent Comments
03-29 00:00
관리 메뉴

동글동글 라이프

N번째로 발생하는 매치 찾기. 본문

개발자 이야기/Perl

N번째로 발생하는 매치 찾기.

동글동글라이프 2008. 10. 7. 03:50

perl 쿡북에 있는 예제중 뼈가대고 살이되는 것들을 골라내어 정리해보았다.


1. 정규표현식을 사용하여 통해서 3번째 값을 찾는 코드이다.

if문을 적절하게 사용하였고 /g 변경자를 사용하여 전체 매치를 시켜 3번째 값을 찾아냈다.

1
2
3
4
5
6
7
8
9
use strict;
$_ = "one fish two fish red fish blue fish";
my $WANT = 3;
my $count = 0;
while(/(\w+)\s+fish\b/gi){
	if(++$count ==$WANT){
		print "The Third fish is a $1 one.";
	}
}


1
The Third fish is a red one.


2. 일치한 문자중  짝수번째 fish를 찾아낸다.

grep은 매치하는 요소를 추출하여 배열에 저장한다.
@foo = grep(!/^#/, @bar);    # weed out comments
 @foo = grep {!/^#/} @bar;    # weed out comments

count 변수가 1씩 증가하면서 짝수일 경우의 값을 저장한다.

1
2
3
$_ = "one fish two fish red fish blue fish";
@evens = grep { $count++ %2 == 1} /(\w+)\s+fish\b/gi;
print "Even numbered fish are ( @evens )\n";


1
Even numbered fish are ( two blue )


3. 치환 작업 

정규표현식에 if문도 있고 ... 정말 신기한 코드가 아닌가!!

4번째 매치되는 fish 앞의 문자열을 sushi로 치환하는 코드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$_ = "one fish two fish red fish blue fish";
my $count = 0;
s{
	\b
	(\w+)
	(
	\s+fish\b
	)
}{
	if(++$count==4){
	"sushi". $2;
	} else {
	$1 . $2;
	}
}gex;
print 


4. 마지막 일치하는 값을 구하는 코드

매치된 값을 리스트로 만들고 거기에 [-1]의 값을 저장하는 발상 자체가 흥미롭다.

1
2
3
$_ = "one fish two fish red fish blue fish";
$last = (/\b(\w+)\s+fish\b/gi)[-1];
print "Last fish is $last\n";

Output:

1
Last fish is blue


마지막 값을 구하는 또 하나의 코드

/g를 사용하지 않고 마지막 매치를 구하고자 할 때

?! 는 발견되어서는 안되는 코드 Negative lookahead assertion 을 이용한다.

1
2
3
4
5
6
7
8
9
10
$_ = "one fish two fish red fish blue fish";
if(m{
		\b (\w+) \s+ fish \b
		(?! .* \b fish \b)
	}six)
{
	print "Last fish is $1. \n";
}else{
	print "Failed!\n";
}


Output:

1
Last fish is blue. 



'개발자 이야기 > Perl' 카테고리의 다른 글

음악을 들어보자! #2  (2) 2008.10.09
음악을 들어보자!  (1) 2008.10.08
Chapter 4. Getting Started  (3) 2008.10.07
Tutorial Availability & Introduction  (0) 2008.10.07
프로야구 순위 출력  (2) 2008.10.07
Comments