[英]How to replace every 4th character of a string using .gsub in Ruby?
Beginner here, obviously.显然,这里是初学者。 I need to add a sum and a string together and from the product, I have to replace every 4th character with underscore, the end product should look something like this: 160_bws_np8_1a
我需要将一个总和和一个字符串加在一起,从产品中,我必须用下划线替换每个第 4 个字符,最终产品应该如下所示:160_bws_np8_1a
I think .gsub is the way, but I can find a way to format the first part in .gsub where I have to specify every 4th character.我认为 .gsub 是一种方式,但我可以找到一种方法来格式化 .gsub 中的第一部分,我必须指定每个第 4 个字符。
total = (1..num).sum
final_output = "#{total.to_s}" + "06bwsmnp851a"
return final_output.gsub(//, "_")
This would work:这会起作用:
s = '12345678901234'
s.gsub(/(...)./, '\1_')
#=> "123_567_901_34"
The regex matches 3 characters ( ...
) that are captured (parentheses) followed by another character ( .
).正则表达式匹配捕获的 3 个字符 (
...
)(括号),后跟另一个字符 ( .
)。 Each match is replaced by the first capture ( \1
) and a literal underscore ( _
).每个匹配都被第一个捕获(
\1
)和文字下划线( _
)替换。
s = "12345678901234"
Here are two ways to do that.这里有两种方法可以做到这一点。 Both return
两者都返回
"123_567_901_34"
Match every four-character substring and replace the match with the first three characters of the match followed by an underscore匹配每四个字符的子字符串并将匹配替换为匹配的前三个字符,后跟下划线
s.gsub(/.{4}/) { |s| s[0,3] << '_' }
Chain the enumerator s.gsub(/./)
to Enumerator#with_index and replace every fourth character with an underscore将枚举
s.gsub(/./)
到Enumerator#with_index并用下划线替换每四个字符
s.gsub(/./).with_index { |c,i| i%4 == 3 ? '_' : c }
See the form of String#gsub that takes a single argument and no block.请参阅采用单个参数且没有块的String#gsub的形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.