2

我有一个字符串 thisLine,它包含 11 个用空格分隔的数字。我只想获得第一个数字。我尝试了命令:

grep('\\d*\\.\\d*',thisLine,value=TRUE)

它返回整个字符串,而不是第一个数字。如何只返回第一个数字?

4

2 回答 2

6

我相信有很多可能性,这里有一些我会考虑的:

thisLine <- paste(runif(11), collapse = " ")
thisLine
# [1] "0.841216114815325 0.861485596280545 0.973681036382914 0.683699210174382 0.95226536039263 0.368689567316324 0.173984130611643 0.497511914698407 0.870743532432243 0.45606177020818 0.222731305286288"

sub("\\s+.*", "", thisLine)              # assumes no leading space
sub("\\s*(\\S+?)\\s.*", "\\1", thisLine) # handles leading spaces
strsplit(thisLine, " ")[[1]][1]          # more flexible if you want 2nd, 3rd, ...

都给

# [1] "0.841216114815325"
于 2012-12-22T14:29:12.267 回答
1

str_first_number()您可以使用包中的功能很好地做到这一点strex

library(strex)
johnsmith <- "John Smith, 34 years of age, 6ft tall, 85kg."
str_first_number(johnsmith)
#> [1] 34
str_nth_number(johnsmith, n = 1)  # first number
#> [1] 34
str_nth_number(johnsmith, n = 2)  # second number
#> [1] 6
str_nth_number(johnsmith, n = -1)  # last number
#> [1] 85
str_last_number(johnsmith)
#> [1] 85

reprex 包(v0.2.0)于 2018 年 9 月 3 日创建。

于 2017-02-23T19:21:39.963 回答