r - Match everything up until first instance of a colon
问题描述
Trying to code up a Regex in R to match everything before the first occurrence of a colon.
Let's say I have:
time = "12:05:41"
I'm trying to extract just the 12. My strategy was to do something like this:
grep(".+?(?=:)", time, value = TRUE)
But I'm getting the error that it's an invalid Regex. Thoughts?
解决方案
在我看来,您的正则表达式似乎很好,我认为您不应该使用 grep,而且您丢失perl=TRUE
了这就是您收到错误的原因。
我建议使用:
stringr::str_extract( time, "\\d+?(?=:)")
grep 与这里使用的略有不同,它适用于匹配单独的值并过滤掉具有相似模式的值,但您不能使用 grep 提取字符串中的值。
如果您想使用 Base R,您也可以选择sub
:
sub("^(\\d+?)(?=:)(.*)$","\\1",time, perl=TRUE)
此外,您可以使用 strsplit 拆分字符串并过滤掉第一个字符串,如下所示:
strsplit(time, ":")[[1]][1]
推荐阅读
- flutter - 如何在颤动的扩展磁贴列表中包含单选按钮
- javascript - 如何将 React 类组件转换为函数组件
- azure-machine-learning-service - ModuleNotFoundError:Azure ML 管道中没有名为“keras”的模块
- asp.net-core - 如何在 linux 上生成合理大小的 .NET Core 进程的内存转储文件?
- codeigniter - 饼图chart.js未满
- typescript - 从类型中获取泛型类型
- elasticsearch - Kibana:聚合“日期直方图”无法正常工作
- bash - 在 bash 中进行计数和拆分
- asp.net-core - 在 .net Core 中使用 JWT 进行跨域单点登录 (SSO)
- python - 如何恢复不属于主列表的类别名称?