2012-01-23 274 views
1

我有一个正则表达式设置$ 1:它对应于()之间的文本:the_beginning(.*)the_end字符串替换正则表达式

我想用somethingelse替换对应于$ 1的值,而不是所有的正则表达式。

在真实的语境

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\";" 

注意,这需要一个正则表达式实际上不匹配的前/后的文本之后。

如果你需要指定范围,而不是内容,可以使用零宽度回顾后/前瞻:

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

我只想替换“123456789”,就像你用'p str.sub /(the_beginning).+?(the_end)/','1 new middle \ 2''所做的那样。我只是想,有一个更好的解决方案来做到这一点 – louiscoquio

+0

@louiscoquio啊,让我为你做一个编辑。 – Phrogz