2011-08-09 8 views
3

이 텍스트가 포함 된 텍스트 파일이 있습니다.루비에서 두 문자열 사이에 텍스트를 가져 오는 방법은 무엇입니까?

What's New in this Version 
========================== 
-This is the text I want to get 
-It can have 1 or many lines 
-These equal signs are repeated throughout the file to separate sections 

Primary Category 
================ 

그냥 모든 것을 얻고 싶습니다. =============== = 및 Primary Category를 선택하고 해당 텍스트 블록을 변수에 저장합니다. 다음과 같은 일치 메서드가 작동 할 것이라고 생각했지만 NoMethodError : undefined method`match '

 f = File.open(metadataPath, "r") 
    line = f.readlines 
    whatsNew = f.match(/==========================(.*)Primary Category/m).strip 

어떤 아이디어가 있습니까? 미리 감사드립니다.

+0

ruby ​​regexps가 perl과 비슷한 동작을하는 경우 // m 수정자를 사용하지 않고 // 사용하고 싶습니다. \ n도 포함하십시오. // m (perl에서 적어도)은 ^와 $ match를 수정하는 방식이 다릅니다. –

답변

4

f은 파일 설명자입니다. 파일의 텍스트와 일치시키고 싶은 파일은 line입니다. 하나의 문자열로 읽어 내가 (에 정규식하기 어렵다) 배열로 텍스트를 읽는 대신 할 선호입니다 :

-This is the text I want to get \n-It can have 1 or many lines\n-These equal signs are repeated throughout the file to separate sections" 
:

contents = File.open(metadataPath) { |f| f.read } 
contents.match(/==========================(.*)Primary Category/m)[1].strip 

마지막 줄은 원하는 출력을 생성

+0

이것은 트릭을 했어! 감사! – Abdulla

0
f = File.open(metadataPath, "r") 
line = f.readlines 
line =~ /==========================(.*)Primary Category/m 
whatsNew = $1 

당신은 정제 고려할 수 . *하지만 그 욕심 수 있기

0

귀하의 문제는 readlines도 당신에게 strin의 배열을 제공한다는 것입니다 gs (각 줄마다 하나씩)하지만, 사용하는 정규 표현식에는 단일 문자열이 필요합니다.

contents = File.read(metadataPath) 
puts contents[/^=+(.*?)Primary Category/m] 
# => ========================== 
# => -This is the text I want to get 
# => -It can have 1 or many lines 
# => -These equal signs are repeated throughout the file to separate sections 
# => 
# => Primary Category 

또는 정규 표현식 적용하기 전에 단일 문자열로 라인을 가입 할 수 :

lines = File.readlines(metadataPath) 
puts lines.join[/^=+(.*?)Primary Category/m] 
# => ========================== 
# => -This is the text I want to get 
# => -It can have 1 or many lines 
# => -These equal signs are repeated throughout the file to separate sections 
# => 
# => Primary Category 
0

내가 걸릴 것 접근 방식은 라인 읽기 당신은 하나의 문자열로 파일을 읽을 수 어떤 라인 번호가 등호 시리즈 (Array#find_index을 사용)인지 알아 내고 다음 라인의 등호 다음에 등호 (예 : Enumerable#each_cons(2)을 사용하기 전)에 라인을 묶음으로 그룹화하십시오 및 map). 그렇게하면 섹션 제목이 바뀌면 많이 수정할 필요가 없습니다.

관련 문제