ruby - 如何从句子中获取特定的字符串
问题描述
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
。
解决方案
使用这个正则表达式:
str = "My working time is: 12 hours and the job is finished"
match = str.match(%r{.* time is: (\d+).*})
match[1] => "12"
因此,它将time is:
在字符串中找到并捕获该短语之后的所有数字,但不会捕获其他数字(如果存在)。
推荐阅读
- angular - angular2如何在未字符串化的div中显示属性值
- rest - 简单(和)脏 Firestore 身份验证规则
- elasticsearch - Couchbase Elasticsearch 连接器保存检查点相同的存储桶
- android - Android Studio Gradle 更新失败并给出项目错误
- makefile - make: *** 没有规则来制作目标“watch_scss”。停止
- mongodb - 将当前日期应用于 MongoDB 聚合中的方程式
- jquery - 显示对话框时设置 AlertifyJS 回调
- odoo - 如何在odoo中的复选框中设置默认值
- xamarin.forms - Vimeo 未在 Xamarin.android 中显示全屏选项
- java - 带有微服务的春季云流