Ruby:将字符插入字符串?

时间:2015-02-16 15:44:49

标签: ruby

1
00:00:00000  -->00:00:00000
2
00:00:00730  -->00:00:04280
So when Sam originally sent me an email to do this course,  
3
00:00:04280  -->00:00:08400
he said Ben can you teach a 50 minute course on management.

我想在,中插入:00730,因此它变为:00,730。我怎么能这样做?

我正在考虑

  path = 'lib/subtitle.txt'
  lines = IO.readlines(path).map do |line|
    *if contains 5 number, then insert a comma into it, like `gsub?`
  end
  File.open(path, 'w') do |file|
    file.puts lines
  end

但我对Regex不是很熟悉,有没有更简单的方法呢?

1 个答案:

答案 0 :(得分:2)

使用正则表达式 - 捕获组和反向引用(String#gsub):

"00:00:04280  -->00:00:08400".gsub(/(\d{2})(\d{3})/, '\1,\2')
# => "00:00:04,280  -->00:00:08,400"

捕获组(...)可以在替换字符串中引用\1\2(引用第一个,第二个捕获的组)