Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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中括号中的数字_R_Regex - Fatal编程技术网

使用正则表达式提取R中括号中的数字

使用正则表达式提取R中括号中的数字,r,regex,R,Regex,我试图从以下内容中提取22: "Feb22 19 (22) 100 (Weeklys) " 我试过下面的方法,但没有成功。有什么建议吗 grep("\\(.*\\)", "Feb22 19 (22) 100 (Weeklys) ", value= TRUE 我们可以尝试对捕获组使用sub: x <- "Feb22 19 (22) 100 (Weeklys) " sub(".*\\((\\d+)\\).*", "\\1", x) [1] "22" 替换为\\1,这是模式中

我试图从以下内容中提取22:

"Feb22 19  (22) 100  (Weeklys) "
我试过下面的方法,但没有成功。有什么建议吗

grep("\\(.*\\)", "Feb22 19  (22) 100  (Weeklys) ", value= TRUE

我们可以尝试对捕获组使用
sub

x <- "Feb22 19  (22) 100  (Weeklys) "
sub(".*\\((\\d+)\\).*", "\\1", x)

[1] "22"

替换为
\\1
,这是模式中捕获的数字。请注意,如果输入不包含括号中的数字,则上面对
sub
的调用将实际返回原始输入字符串。如果您不喜欢这种行为,那么您将不得不做更多的工作。

我们可以尝试对捕获组使用
sub

x <- "Feb22 19  (22) 100  (Weeklys) "
sub(".*\\((\\d+)\\).*", "\\1", x)

[1] "22"
替换为
\\1
,这是模式中捕获的数字。请注意,如果输入不包含括号中的数字,则上面对
sub
的调用将实际返回原始输入字符串。如果您不喜欢这种行为,那么您将不得不做更多的工作。

我们还可以使用:

    string<-"Feb22 19 (22) 100 (Weeklys) "
    unlist(stringr::str_extract_all(string,"\\d{1,}(?=\\))"))
    #[1] "22"
我们还可以使用:

    string<-"Feb22 19 (22) 100 (Weeklys) "
    unlist(stringr::str_extract_all(string,"\\d{1,}(?=\\))"))
    #[1] "22"