[英]How to find and save a string section in ruby on rails 4?
I need to find a section of a string that includes the substring "print time:"
and save it with the time it displays after the colon on the database. 我需要找到包含子字符串"print time:"
的字符串的一部分,并将其与在数据库中冒号之后显示的时间一起保存。
What I've used until now is the downcase
helper and the includes?
到目前为止,我使用的是downcase
帮助程序及其includes?
helper to start the search but I'm not sure how to actually execute a search inside the string. 帮助程序开始搜索,但是我不确定如何在字符串中实际执行搜索。
How can I find the section of the string so that I can save it afterwards? 如何找到字符串的一部分,以便以后保存它?
Use regular expressions , which in Ruby can be written with the /…/
syntax and matched against using String#match
. 使用正则表达式 ,在Ruby中可以使用/…/
语法编写正则表达式 ,并使用String#match
。
log = "username: jsmith\nprint time: 08:02:41\npower level: 9001"
print_time = log.match(/print time:\s*([^\n]+)\s*\n/)[1]
p print_time # => "08:02:41"
The regex /print time:\\s*([^\\n]+?)\\s*\\n/
matches any text after “print time:”, on the same line, ignoring surrounding whitespace \\s*
, and saves it as the first capture group using the ()
. 正则表达式/print time:\\s*([^\\n]+?)\\s*\\n/
匹配“ print time:”之后的任何文本,并忽略同一行\\s*
,并将其另存为第一个捕获组使用()
。 Then [1]
selects the contents of that first capture group. 然后[1]
选择该第一个捕获组的内容。
After extracting the print_time
string, you can do whatever you need to with it. 提取print_time
字符串后,您可以使用它进行任何操作。 For example, if you had a Rails model PrintTime
, you might save the extracted time to the database with PrintTime.create(extracted_time: print_time)
. 例如,如果您有Rails模型PrintTime
,则可以使用PrintTime.create(extracted_time: print_time)
将提取的时间保存到数据库PrintTime.create(extracted_time: print_time)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.