2012-01-23 5 views
1

$ 1을 설정하는 정규 표현식이 있습니다. () 사이의 텍스트는 the_beginning(.*)the_end 사이에 해당합니다.문자열을 정규 표현식으로 대체

모든 정규식이 아닌 $ 1에 해당하는 값을 somethingelse으로 바꾸고 싶습니다. 실제 상황에서

:

my_string에는 다음이 포함

/* MyKey */ = { [code_missing]; MY_VALUE = "123456789"; [code_missing]; }

내가 "123456789"를 교체하려면 (예 : "987654321"로). 난 아직도 당신이 원하는 정확히 모르겠어요

"/\\* MyKey \\*/ = {[^}]*MY_VALUE = \"(.*)\";"

+1

코드를 게시 할 수 있습니까? –

답변

3

, 그러나 여기에서 당신에게 도움이 될 몇 가지 코드입니다 : 는 그리고 이것은 내 정규 표현식입니다

str = "Hello this is the_beginning that comes before the_end of the string" 
p str.sub /the_beginning(.+?)the_end/, 'new_beginning\1new_end' 
#=> "Hello this is new_beginning that comes before new_end of the string" 

p str.sub /(the_beginning).+?(the_end)/, '\1new middle\2' 
#=> "Hello this is the_beginningnew middlethe_end of the string" 

편집 :

theDoc = '/* MyKey */ = { [code_missing]; MY_VALUE = "123456789";' 
regex = %r{/\* MyKey \*/ = {[^}]*MY_VALUE = "(.*)";} 
p theDoc[ regex, 1 ] # extract the captured group 
#=> "123456789" 

newDoc = theDoc.sub(regex, 'var foo = \1') 
#=> "var foo = 123456789" # replace, saving the captured information 

편집 # 2 : 정보에 액세스하기 일치 전/후에 일치

regex = /\d+/ 
match = regex.match(theDoc) 
p match.pre_match, match[0], match.post_match 
#=> "/* MyKey */ = { [code_missing]; MY_VALUE = \"" 
#=> "123456789" 
#=> "\";" 

newDoc = "#{match.pre_match}HELLO#{match.post_match}" 
#=> "/* MyKey */ = { [code_missing]; MY_VALUE = \"HELLO\";" 

실제로는 사전/사후 텍스트와 일치하지 않는 정규식이 필요합니다. 당신은 제한이 아닌 내용을 지정해야하는 경우

, 당신은 제로 폭 lookbehind/내다 사용할 수 있습니다

regex = /(?<=the_beginning).+?(?=the_end)/ 
m = regex.match(str) 
"#{m.pre_match}--new middle--#{m.post_match}" 
#=> "Hello this is the_beginning--new middle--the_end of the string" 

을 ...하지만 지금은 캡처 및 \1\2를 사용하는 것보다 분명히 더 많은 작업이다 . 나는 당신이 찾고있는 것을 완전히 이해하고 있는지, 왜 그것이 더 쉬울 것이라고 생각하는지 확신 할 수 없다.

+0

맞지만, 왼쪽과 오른쪽 부분을 복사하는 대신 직접 편집을 허용하는 더 깨끗한 버전이 있습니까? – louiscoquio

+0

'p str.sub /(the_beginning).+((the_end)/, '\ 1new middle \ 2''처럼 "123456789"를 대체하고 싶습니다. 나는 거기에 더 좋은 해결책이 있다고 생각하고 있었다. – louiscoquio

+0

@louiscoquio 아, 내가 편집 해 줄게. – Phrogz

관련 문제