首页 > 解决方案 > 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?

标签: rregex

解决方案


在我看来,您的正则表达式似乎很好,我认为您不应该使用 grep,而且您丢失perl=TRUE了这就是您收到错误的原因。

我建议使用:

stringr::str_extract( time, "\\d+?(?=:)")

grep 与这里使用的略有不同,它适用于匹配单独的值并过滤掉具有相似模式的值,但您不能使用 grep 提取字符串中的值。

如果您想使用 Base R,您也可以选择sub

sub("^(\\d+?)(?=:)(.*)$","\\1",time, perl=TRUE)

此外,您可以使用 strsplit 拆分字符串并过滤掉第一个字符串,如下所示:

strsplit(time, ":")[[1]][1]

推荐阅读