, 그러나 여기에서 당신에게 도움이 될 몇 가지 코드입니다 : 는 그리고 이것은 내 정규 표현식입니다
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
를 사용하는 것보다 분명히 더 많은 작업이다 . 나는 당신이 찾고있는 것을 완전히 이해하고 있는지, 왜 그것이 더 쉬울 것이라고 생각하는지 확신 할 수 없다.
코드를 게시 할 수 있습니까? –