正则表达式匹配导出函数中的包

时间:2017-10-06 04:19:52

标签: r regex

我正在尝试创建一个从脚本中提取包名称的函数。到目前为止,我已经能够使用 public Cursor fetchdatabyfilter(String inputText) { Cursor row = null; String query = "SELECT * FROM "+TABLE_NAME; SQLiteDatabase db = this.getReadableDatabase(); if (inputText == null || inputText.length () == 0) { row = db.rawQuery(query, null); }else { query = "SELECT * FROM "+TABLE_NAME+" WHERE "+COL_2+" like '%"+inputText+ "%'"+"OR "+COL_3+" like '%"+inputText+ "%'"; row = db.rawQuery(query, null); } if (row != null) { row.moveToFirst(); } return row; } library提取所有加载的包。我还注意到有时我使用require运算符来使用函数。对于这些情况,我有以下情况但不起作用:

::

在这个例子中;我想将a <- c( "ggplot2::aes()", " digest::digest(data))", " data <- dplyr::rbind_all(data)" ) gsub('^(.+)::(.+)', '\\1', a) 作为向量返回。

3 个答案:

答案 0 :(得分:1)

要从字符串中提取包名称,请使用regmatchesregexec函数。

第1步:在::

之前提取条款
s1 <- regmatches(a, regexec("^.*?::",a))
> s1
[[1]]
[1] "ggplot2::"

[[2]]
[1] "                      digest::"

[[3]]
[1] "  data <- dplyr::"

解释

    ^ asserts position at start of a line
    .*? matches any character (except for line terminators)
    *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
    :: matches the characters :: literally (case sensitive)   

step2 :在::之前替换<-,空格和术语,

s2 <- gsub(".*(<-)|::| ","",s1)
> s2
[1] "ggplot2" "digest"  "dplyr"

答案 1 :(得分:0)

您可以使用str_extract

out <- str_extract("data <- dplyr::rbind_all(data)", regex("[a-zA-Z]+::"))
> substr(out, 1, (nchar(out)-2))
[1] "dplyr" 

> out <- str_extract("digest::digest(data))", regex("[a-zA-Z]+::"))
> substr(out, 1, (nchar(out)-2))
[1] "digest"
> 

答案 2 :(得分:0)

你可以这样做:

## Your data:
a <- c("ggplot2::aes()",
        "   data.table::dcast(data, time ~ variable, fun = mean)",
        "  data <- dplyr::rbind_all(data)")

## Extract string that consists of letters, numbers or a dot
## and has at least two characters (= package naming conventions),
## and that is followed by "::"
stringr::str_extract(a, "[[:alnum:].]{2,}(?=::)")
# [1] "ggplot2"    "data.table" "dplyr"