我有一个regexp设置$1 :它对应于(和)在:the_beginning(.*)the_end中的文本。
我想用somethingelse替换与$1对应的值,而不是所有regexp。
实际上下文中的:
my_string包含:
/* MyKey */ = { [code_missing]; MY_VALUE = "123456789"; [code_missing]; }
我想把"123456789“替换为"987654321”(例如)。这是我的雷杰普:
"/\\* MyKey \\*/ = {[^}]*MY_VALUE = \"(.*)\";"
发布于 2012-01-23 21:44:59
我仍然不确定你到底想要什么,但以下是一些应该能帮助你的代码:
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。我不确定我完全明白你在寻找什么,为什么你认为这会更容易。
https://stackoverflow.com/questions/8978981
复制相似问题