首页 > 解决方案 > 如何从句子中获取特定的字符串

问题描述

Rails 中从句子中获取特定字符串的最佳方法是什么?

例如,我有:

"My working time is: 3 hours and the job is finished"
"Bla2 time is: 6 hours and the job is still pending"
"Bla bla bla time is: 7 hours and the job is finished"

我想在 words 后面取数字"time is: ",所以预期的输出只有数字,如:3, 6, 7

标签: ruby

解决方案


使用这个正则表达式:

str = "My working time is: 12 hours and the job is finished"

match = str.match(%r{.* time is: (\d+).*})
match[1] => "12"

因此,它将time is:在字符串中找到并捕获该短语之后的所有数字,但不会捕获其他数字(如果存在)。


推荐阅读