如何从文本中提取数字? [英] How to extract numbers from text?

查看:150
本文介绍了如何从文本中提取数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有文字流淌的字符串:

i have the flowing text string:

string <- "['CBOE SHORT-TERM VIX FUTURE DEC 2016', 81.64],\n\n    ['CBOE SHORT-TERM VIX FUTURE JAN 2017', 18.36]"

是否有一种无需使用即可从文本中提取数字元素的简单方法:

is there a simple way of extracting numerical elements from text without having to use:

string_table <- strsplit(string, " ")

,然后选择第n个元素并继续 strsplit 直到我拥有所需的内容。

and then select n-th element and continue to strsplit until i have what i need.

结果应为:

result <- c(2016, 81, 64, 2017, 18, 36)

谢谢。

推荐答案

我们可以通过将模式指定为一个或多个来使用 str_extract_all 数字( [0-9] + )。输出将是长度为1的列表,用 [[>提取向量并转换为数字

We can use str_extract_all by specifying the pattern as one or more number ([0-9]+). The output will be a list of length 1, extract the vector with [[ and convert to numeric.

library(stringr)
as.numeric(str_extract_all(string, "[0-9]+")[[1]])
#[1] 2016   81   64 2017   18   36

如果我们使用 strsplit ,除以非数字字符

If we are using strsplit, split by the non-numeric characters

as.numeric(strsplit(string, "\\D+")[[1]][-1])
#[1] 2016   81   64 2017   18   36

这篇关于如何从文本中提取数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆