簡體   English   中英

Ruby:在字符串中插入一個字符?

[英]Ruby: Insert a character into a string?

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不太熟悉,有沒有更簡單的方法?

使用正則表達式-捕獲組和反向引用( 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替換字符串引用(引用第一個,第二個捕獲組)

您也可以簡單地運行

`sed -i.bak 's/^\([[:digit:]]\{2\}:[[:digit:]]\{2\}:[[:digit:]]\{2\}\)\([[:digit:]]\{3\}  -->[[:digit:]]\{2\}:[[:digit:]]\{2\}:[[:digit:]]\{2\}\)\([[:digit:]]\{3\}\)$/\1,\2,\3/' lib/subtitle.txt `

這將創建備份文件並進行所需的更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM