2014-01-28 2 views
1

나는 후속 조치로 this question으로 돌아왔다. 의 내가 텍스트를괄호 텍스트 캡쳐 (Perl RegEx)

====Example 1==== 
Some text that I want to get that 
may include line breaks 
or special [email protected]#$%^&*() characters 

====Example 2==== 
Some more text that I don't want to get. 

가 있다고 가정하고 시도하고 네 개의 등호를 "==== 예 1 ===="에서 모든 것을 얻을 수 $output = ($text =~ ====Example 1====\s*(.*?)\s*====);를 사용하자 바로 "예 2"전에.

내가 본 on this site, regexpal.com에 기반하여 Perl은 텍스트를 찾아서 일치 시키지만 $ 출력은 null이거나 "1"로 할당됩니다. 캡쳐 괄호로 뭔가 잘못하고 있다고 확신하지만, 무엇을 알아 내지 못합니다. 어떤 도움을 주시면 감사하겠습니다. 내 전체 코드는 다음과 같습니다 괄호

$text = "====Example 1====\n 
Some text that I want to get this text\n 
may include line breaks\n 
or special [email protected]#$%^&*() characters\n 
\n 
====Example 2====]\n 
Some more filler text that I don't want to get."; 
my ($output) = $text =~ /====Example 1====\s*(.*?)\s*====/; 
die "un-defined" unless defined $output; 
print $output; 
+2

내 ($ 출력) = $ text = ~/==== 예제 1 ==== \ s * (. *?) \ s * ==== /; –

답변

1

두 가지.

  1. /s 플래그를 정규식에 적용하면 정규식의 입력이 여러 줄이 될 수 있음을 알 수 있습니다.
  2. 괄호를 ($text ~= regex); 대신 약 $output으로 바꿉니다.

는 예 :

같은 스크립트로 퍼팅 예를 들어

($output) = $text =~ /====Example\s1====\s*(.*?)\s*====/s;

:

#!/usr/bin/env perl 

$text=" 
====Example 1==== 
Some text that I want to get that 
may include line breaks 
or special [email protected]#$%^&*() characters 

====Example 2==== 
Some more text that I don't want to get. 
"; 

print "full text:","\n"; 
&hr; 
print "$text","\n"; 
&hr; 

($output) = $text =~ /====Example\s1====\s*(.*?)\s*====/s; 
print "desired output of regex:","\n"; 
&hr; 
print "$output","\n"; 
&hr; 

sub hr { 
     print "-" x 80, "\n"; 
} 

는 잎이 마음에 출력 :

bash$ perl test.pl 
-------------------------------------------------------------------------------- 
full text: 
-------------------------------------------------------------------------------- 

====Example 1==== 
Some text that I want to get that 
may include line breaks 
or special [email protected]#0^&*() characters 

====Example 2==== 
Some more text that I don't want to get. 

-------------------------------------------------------------------------------- 
desired output of regex: 
-------------------------------------------------------------------------------- 
Some text that I want to get that 
may include line breaks 
or special [email protected]#0^&*() characters 
-------------------------------------------------------------------------------- 
+0

고마워, 수정 프로그램이 작동했습니다. – KingBob

3

시도가리스트 문맥을 강제 등 .도 줄 바꿈을 일치시킬 수 있습니다 일치시킬 때 /s을 사용,

my ($output) = $text =~//s; 
+0

시도했지만 '$ output'은 여전히 ​​null입니다. – KingBob

+1

@KingBob 확인 업데이트 –

+0

완벽하게 작동합니다! 감사! – KingBob