为什么这个Ruby不能取代regex ?

时间:2022-12-13 21:44:42

Consider the following string which is a C fragment in a file:

考虑以下字符串,它是文件中的C片段:

strcat(errbuf,errbuftemp);

I want to replace errbuf (but not errbuftemp) with the prefix G-> plus errbuf. To do that successfully, I check the character after and the character before errbuf to see if it's in a list of approved characters and then I perform the replace.

我想用前缀G->加上errbuf替换errbuf(但不是errbuftemp)。为了成功地完成这个任务,我检查了在errbuf之前和字符之前的字符,看看它是否在被批准的字符列表中,然后执行替换。

I created the following Ruby file:

我创建了以下Ruby文件:

line = " strcat(errbuf,errbuftemp);"  
item = "errbuf"  
puts line.gsub(/([ \t\n\r(),\[\]]{1})#{item}([ \t\n\r(),\[\]]{1})/, "#{$1}G\->#{item}#{$2}")

Expected result:

预期结果:

strcat(G->errbuf,errbuftemp);

Actual result

实际结果

strcatG->errbuferrbuftemp);

Basically, the matched characters before and after errbuf are not reinserted back with the replace expression.

基本上,errbuf前后的匹配字符不会与替换表达式一起重新插入。

Anyone can point out what I'm doing wrong?

谁能指出我做错了什么?

2 个解决方案

#1


3  

Because you must use syntax gsub(/.../){"...#{$1}...#{$2}..."} or gsub(/.../,'...\1...\2...').

因为你必须使用语法gsub(/…/)# { $ 1 } {“……# { $ 2 }…“}或gsub(/…/,“……1 \ \ 2…”)。

Here was the same problem: werid, same expression yield different value when excuting two times in irb

这里有一个同样的问题:werid,当在irb中挖掘两次时,相同的表达式会产生不同的值

The problem is that the variable $1 is interpolated into the argument string before gsub is run, meaning that the previous value of $1 is what the symbol gets replaced with. You can replace the second argument with '\1 ?' to get the intended effect. (Chuck)

问题是,在运行gsub之前,变量$1被插入到参数字符串中,这意味着之前的$1的值是符号被替换的值。您可以用“\1 ?”替换第二个参数,以获得预期的效果。(夹头)

#2


0  

I think part of the problem is the use of gsub() instead of sub().

我认为部分问题是使用gsub()而不是sub()。

Here's two alternates:

这是两个交替:

str = 'strcat(errbuf,errbuftemp);'

str.sub(/\w+,/) { |s| 'G->' + s } # => "strcat(G->errbuf,errbuftemp);"
str.sub(/\((\w+)\b/, '(G->\1') # => "strcat(G->errbuf,errbuftemp);"

#1


3  

Because you must use syntax gsub(/.../){"...#{$1}...#{$2}..."} or gsub(/.../,'...\1...\2...').

因为你必须使用语法gsub(/…/)# { $ 1 } {“……# { $ 2 }…“}或gsub(/…/,“……1 \ \ 2…”)。

Here was the same problem: werid, same expression yield different value when excuting two times in irb

这里有一个同样的问题:werid,当在irb中挖掘两次时,相同的表达式会产生不同的值

The problem is that the variable $1 is interpolated into the argument string before gsub is run, meaning that the previous value of $1 is what the symbol gets replaced with. You can replace the second argument with '\1 ?' to get the intended effect. (Chuck)

问题是,在运行gsub之前,变量$1被插入到参数字符串中,这意味着之前的$1的值是符号被替换的值。您可以用“\1 ?”替换第二个参数,以获得预期的效果。(夹头)

#2


0  

I think part of the problem is the use of gsub() instead of sub().

我认为部分问题是使用gsub()而不是sub()。

Here's two alternates:

这是两个交替:

str = 'strcat(errbuf,errbuftemp);'

str.sub(/\w+,/) { |s| 'G->' + s } # => "strcat(G->errbuf,errbuftemp);"
str.sub(/\((\w+)\b/, '(G->\1') # => "strcat(G->errbuf,errbuftemp);"