簡體   English   中英

使用Ruby on Rails在多個點中拆分字符串

[英]Splitting a String in Multiple points using Ruby on Rails

我的數據庫中有一個字符串代表用戶的注釋。 我想拆分這個字符串,這樣我就可以將每個音符分成內容,用戶和日期。

這是String的格式:

"Example Note <i>Josh Test 12:53 PM on 8/14/12</i><br><br> Another example note <i>John Doe 12:00 PM on 9/15/12</i><br><br>  Last Example Note <i>Joe Smoe 1:00 AM on 10/12/12</i><br><br>" 

我需要把它分成一個數組

["Example Note",  "Josh Test", "12:53 8/14/12", "Another example note", "John Doe", "12:00 PM 9/15/12", "Last Example Note", "Joe Smoe", "1:00 AM 10/12/12"]

我還在試驗這個。 任何想法都非常歡迎,謝謝! :)

您可以使用正則表達式來實現更簡單的方法。

s = "Example Note <i>Josh Test 12:53 PM on 8/14/12</i><br><br> Another example note <i>John Doe 12:00 PM on 9/15/12</i><br><br>  Last Example Note <i>Joe Smoe 1:00 AM on 10/12/12</i><br><br>" 
s.split(/\s+<i>|<\/i><br><br>\s?|(?<!on) (?=\d)/)
=> ["Example Note", "Josh Test", "12:53 PM on 8/14/12", "Another example note", "John Doe", "12:00 PM on 9/15/12", " Last Example Note", "Joe Smoe", "1:00 AM on 10/12/12"]

datetime元素是關閉格式的,但也許可以單獨對它們應用一些格式。

編輯:刪除不必要的+字符。

您可以使用Nokogiri使用Xpath / CSS選擇器解析所需的文本。 為了給你一個簡單的例子,使用簡單的解析來開始,下面將每個i標記映射為數組中的新元素:

require 'nokogiri'

html = Nokogiri::HTML("Example Note <i>Josh Test 12:53 PM on 8/14/12</i><br><br> Another example note <i>John Doe 12:00 PM on 9/15/12</i><br><br>  Last Example Note <i>Joe Smoe 1:00 AM on 10/12/12</i><br><br>")

my_array = html.css('i').map {|text| text.content}
#=> ["Josh Test 12:53 PM on 8/14/12", "John Doe 12:00 PM on 9/15/12", "Joe Smoe :00 AM on 10/12/12"]

使用CSS選擇器,您可以輕松地執行以下操作:

require 'nokogiri'

html = Nokogiri::HTML("<h1>My Message</h1><p>Hi today's date is: <time>Firday, May 31st</time></p>")
message_header = html.css('h1').first.content #=> "My Message"
message_body = html.css('p').first.content #=> "Hi today's date is:"
message_sent_at = html.css('p > time').first.content #=> "Friday, May 31st"

也許這可能有用

require 'date'
require 'time'

text = "Example Note <i>Josh Test 12:53 PM on 8/14/12</i><br><br> Another example note <i>John Doe 12:00 PM on 9/15/12</i><br><br>  Last Example Note <i>Joe Smoe 1:00 AM on 10/12/12</i><br><br>"

notes=text.split('<br><br>')

pro_notes = []

notes.each do |note_e|
  notes_temp = note_e.split('<i>')
  words = notes_temp[1].split(' ')

  temp = words[5].gsub('</i>','')
  a = temp.split('/')

  full_name = words[0] + ' ' + words[1]
  nn = notes_temp[0]
  dt = DateTime.parse(a[2] +'/'+ a[0] +'/'+ a[1] +' '+ words[2])

  pro_notes << [full_name, nn, dt]
end

暫無
暫無

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

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