Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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
Regex 从数字和文本字符串中提取数字_Regex_R_Text Extraction - Fatal编程技术网

Regex 从数字和文本字符串中提取数字

Regex 从数字和文本字符串中提取数字,regex,r,text-extraction,Regex,R,Text Extraction,我在R中有一个data.frame,其中有一列包含形式为{some letters}-{a number}{a letter}的字符串,例如,x用于提取子字符串。使用as.numeric将结果字符串转换为数字: string = 'KFKGDLDSKFDSKJJFDI-4567W' as.numeric(regmatches(string, regexpr('\\d+', string))) # 4567 您可以轻松地使用此选项在数据框中创建新列: #data = data.frame(x =

我在R中有一个data.frame,其中有一列包含形式为{some letters}-{a number}{a letter}的字符串,例如,
x用于提取子字符串。使用
as.numeric
将结果字符串转换为数字:

string = 'KFKGDLDSKFDSKJJFDI-4567W'
as.numeric(regmatches(string, regexpr('\\d+', string)))
# 4567
您可以轻松地使用此选项在数据框中创建新列:

#data = data.frame(x = rep(string, 10))
transform(data, y = as.numeric(regmatches(x, regexpr('\\d+', x))))
#                           x    y
# 1  KFKGDLDSKFDSKJJFDI-4567W 4567
# 2  KFKGDLDSKFDSKJJFDI-4567W 4567
# 3  KFKGDLDSKFDSKJJFDI-4567W 4567
# 4  KFKGDLDSKFDSKJJFDI-4567W 4567
…
试试这个:

gsub("[a-zA-Z]+-([0-9]+)[a-zA-Z]","\\1", "KFKGDLDSKFDSKJJFDI-4567W")
gsub(“[^0-9]+”,“,”KKGDLDSKJJFDI-4567W”)