我的数据库中有一个字符串代表用户的注释。我想拆分这个字符串,这样我就可以将每个注释分成内容、用户和日期。
这是字符串的格式:
"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"]
日期时间元素是非格式的,但单独对它们应用一些格式也许是可以接受的。
编辑:删除了不必要的 +
字符。
关于ruby - 使用 Ruby on Rails 将字符串拆分成多个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16864346/