我有一个文本文件名features.txt,我试图提取一个跟在last_name之后的数字;从每一行。文本文件中有27000行,每行有单词last_name;接下来是数字"介于两者之间没有空格"。
例如:随机文本last_name; 0随机文本
所以我写了
text <- readLines(features.txt)
library(stringr)
lastn <- str_match(text, "last_name;\\d+")
但是这给了&#34; last_name; 0&#34;结果。如何删除&#34; last_name;&#34;从结果中只保留数字。请建议正则表达式或其他方式。
答案 0 :(得分:1)
这只是使用sub
的最简单的解决方案,正如Cath在评论中所建议的那样:
string <- ' random text last_name;0123 random text'
> sub(".+last_name;(\\d+).+", "\\1", string)
[1] "0123"
\\ 1表示模式中括号之间的第一个(在这种情况下是唯一的)表达式(所以\\ d +)
也许有更先进的前瞻性方式,但这很有效。
仅限基数:
string <- ' random text last_name;0 random text'
> gsub('\\D','',regmatches(string,regexpr('last_name;\\d+',string)))
[1] "0"
或使用str_match
中的stringr
:
library(stringr)
> gsub('\\D','',str_match(string,'last_name;\\d+'))
[,1]
[1,] "0"