Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 从字符列表中提取长度为(1 | 2)的数字字符_R_Regex - Fatal编程技术网

R 从字符列表中提取长度为(1 | 2)的数字字符

R 从字符列表中提取长度为(1 | 2)的数字字符,r,regex,R,Regex,我正在抓取PDF中的数据,并尝试搜索长度为1或2的数字字符(1:9)。不幸的是,后面的值在整个PDF中改变了位置,因此我不能简单地调用该值的索引并将其分配给变量 我尝试了许多正则表达式函数,可以从列表中提取数字,但似乎无法实现仅提取特定长度的数字的参数 # Data comes in as a long string Test<-("82026-424 82026-424 1 CSX10 Store Room 75.74 75.74") # Seperate data into indi

我正在抓取PDF中的数据,并尝试搜索长度为1或2的数字字符(1:9)。不幸的是,后面的值在整个PDF中改变了位置,因此我不能简单地调用该值的索引并将其分配给变量

我尝试了许多正则表达式函数,可以从列表中提取数字,但似乎无法实现仅提取特定长度的数字的参数

# Data comes in as a long string
Test<-("82026-424 82026-424 1 CSX10 Store Room 75.74 75.74")

# Seperate data into individual pieces with str_split
Split_Test<-str_split(Test[1],"\\s+")

# We can easily unlist it with the following code (Not sure if needed)
Test_Unlisted<-unlist(Split_Test)

> Test_Unlisted
[1] "82026-424" "82026-424" "1"         "CSX10"     "Store"     "Room"      
[8] "75.74" "75.74"
#数据以长字符串形式输入
测试您需要使用

Test<-("82026-424 82026-424 1 CSX10 Store Room 75.74 75.74, 20")
regmatches(Test, gregexpr("\\b(?<!\\d\\.)\\d{1,2}\\b(?!\\.\\d)", Test, perl=TRUE))

@不幸的是,这个误用给出了与上述str_match()参数类似的结果。它似乎能把两个数字拉到任何地方,比如把82026-424分成“82”“02”“6”“42”…等等。最好的情况是我们只提取真正的长度1或2个数字/字符。非常好,我不认为我可以写正则表达式那么好,所以谢谢你。它可以缩短一点,我更新了answe并添加了解释。
Test_Final<-which(sapply(Test_Unlisted, nchar)==1)
Test<-("82026-424 82026-424 1 CSX10 Store Room 75.74 75.74, 20")
regmatches(Test, gregexpr("\\b(?<!\\d\\.)\\d{1,2}\\b(?!\\.\\d)", Test, perl=TRUE))
library(stringr)
str_extract_all(Test, "\\b(?<!\\d\\.)\\d{1,2}\\b(?!\\.\\d)")