ID EN
String Functions

grep

R Base 3.6.2 🇮🇩 Bahasa Indonesia

grep, grepl, regexpr, gregexpr dan regexec mencari kecocokan dengan pola argumen dalam setiap elemen vektor karakter: keduanya berbeda dalam format dan jumlah detail dalam hasil. sub dan gsub masing-masing melakukan penggantian pertandingan pertama dan semua pertandingan.

Syntax

R
grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE,
     fixed = FALSE, useBytes = FALSE, invert = FALSE)<p></p><p>grepl(pattern, x, ignore.case = FALSE, perl = FALSE,
      fixed = FALSE, useBytes = FALSE)</p><p>sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
    fixed = FALSE, useBytes = FALSE)</p><p>gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
     fixed = FALSE, useBytes = FALSE)</p><p>regexpr(pattern, text, ignore.case = FALSE, perl = FALSE,
        fixed = FALSE, useBytes = FALSE)</p><p>gregexpr(pattern, text, ignore.case = FALSE, perl = FALSE,
         fixed = FALSE, useBytes = FALSE)</p><p>regexec(pattern, text, ignore.case = FALSE, perl = FALSE,
        fixed = FALSE, useBytes = FALSE)</p>

Arguments

Parameter Deskripsi
pattern character string containing a regular expression (or character string for fixed = TRUE) to be matched in the given character vector. Coerced by as.character to a character string if possible. If a character vector of length 2 or more is supplied, the first element is used with a warning. Missing values are allowed except for regexpr and gregexpr.
x, text a character vector where matches are sought, or an object which can be coerced by as.character to a character vector. Long vectors are supported.
ignore.case if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.
perl logical. Should Perl-compatible regexps be used?
value if FALSE, a vector containing the (integer) indices of the matches determined by grep is returned, and if TRUE, a vector containing the matching elements themselves is returned.
fixed logical. If TRUE, pattern is a string to be matched as is. Overrides all conflicting arguments.
useBytes logical. If TRUE the matching is done byte-by-byte rather than character-by-character. See ‘Details’.
invert logical. If TRUE return indices or values for elements that do not match.
replacement a replacement for matched pattern in sub and gsub. Coerced to character if possible. For fixed = FALSE this can include backreferences "\1" to "\9" to parenthesized subexpressions of pattern. For perl = TRUE only, it can also contain "\U" or "\L" to convert the rest of the replacement to upper or lower case and "\E" to end case conversion. If a character vector of length 2 or more is supplied, the first element is used with a warning. If NA, all elements in the result corresponding to matches will be set to NA.

Return Value

grep(value = FALSE) mengembalikan vektor indeks elemen x yang menghasilkan kecocokan (atau tidak, untuk invert = TRUE). Ini akan menjadi vektor bilangan bulat kecuali inputnya adalah vektor panjang, maka itu akan menjadi vektor ganda. grep(value = TRUE) mengembalikan vektor karakter yang berisi elemen x yang dipilih (setelah paksaan, mempertahankan nama tetapi tidak ada atribut lainnya). grep mengembalikan vektor logis (cocok atau tidak untuk setiap elemen x). sub dan gsub mengembalikan vektor karakter dengan panjang dan kecerdasan yang sama

Details

Argumen yang seharusnya berupa string karakter atau vektor karakter dipaksakan ke karakter jika memungkinkan. Masing-masing fungsi ini beroperasi dalam salah satu dari tiga mode: fixed = TRUE: menggunakan pencocokan tepat. perl = TRUE: gunakan ekspresi reguler gaya Perl. fixed = FALSE, perl = FALSE: gunakan ekspresi reguler yang diperluas POSIX 1003.2 (default). Lihat halaman bantuan tentang ekspresi reguler untuk detail berbagai jenis ekspresi reguler. Kedua fungsi *sub hanya berbeda pada sub yang hanya menggantikan kemunculan pertama suatu pola sedangkan gsub menggantikan semua kemunculan. Jika penggantian berisi referensi balik yang tidak ditentukan dalam pola, hasilnya tidak terdefinisi (tetapi paling sering referensi balik dianggap sebagai ""). Untuk regexpr, gregexpr dan regexec kesalahan polanya adalah NA, jika tidak NA

Contoh

Example
R
# NOT RUN {
grep("[a-z]", letters)

txt <- c("arm","foot","lefroo", "bafoobar")
if(length(i <- grep("foo", txt)))
   cat("'foo' appears at least once in\n\t", txt, "\n")
i # 2 and 4
txt[i]

## Double all 'a' or 'b's;  "\" must be escaped, i.e., 'doubled'
gsub("([ab])", "\\1_\\1_", "abc and ABC")

txt <- c("The", "licenses", "for", "most", "software", "are",
  "designed", "to", "take", "away", "your", "freedom",
  "to", "share", "and", "change", "it.",
  "", "By", "contrast,", "the", "GNU", "General", "Public", "License",
  "is", "intended", "to", "guarantee", "your", "freedom", "to",
  "share", "and", "change", "free", "software", "--",
  "to", "make", "sure", "the", "software", "is",
  "free", "for", "all", "its", "users")
( i <- grep("[gu]", txt) ) # indices
stopifnot( txt[i] == grep("[gu]", txt, value = TRUE) )

## Note that in locales such as en_US this includes B as the
## collation order is aAbBcCdDe ...
(ot <- sub("[b-e]",".", txt))
txt[ot != gsub("[b-e]",".", txt)]#- gsub does "global" substitution

txt[gsub("g","#", txt) !=
    gsub("g","#", txt, ignore.case = TRUE)] # the "G" words

regexpr("en", txt)

gregexpr("e", txt)

## Using grepl() for filtering
## Find functions with argument names matching "warn":
findArgs <- function(env, pattern) {
  nms <- ls(envir = as.environment(env))
  nms <- nms[is.na(match(nms, c("F","T")))] # <-- work around "checking hack"
  aa <- sapply(nms, function(.) { o <- get(.)
               if(is.function(o)) names(formals(o)) })
  iw <- sapply(aa, function(a) any(grepl(pattern, a, ignore.case=TRUE)))
  aa[iw]
}
findArgs("package:base", "warn")

## trim trailing white space
str <- "Now is the time      "
sub(" +$", "", str)  ## spaces only
## what is considered 'white space' depends on the locale.
sub("[[:space:]]+$", "", str) ## white space, POSIX-style
## what PCRE considered white space changed in version 8.34: see ?regex
sub("\\s+$", "", str, perl = TRUE) ## PCRE-style white space

## capitalizing
txt <- "a test of capitalizing"
gsub("(\\w)(\\w*)", "\\U\\1\\L\\2", txt, perl=TRUE)
gsub("\\b(\\w)",    "\\U\\1",       txt, perl=TRUE)

txt2 <- "useRs may fly into JFK or laGuardia"
gsub("(\\w)(\\w*)(\\w)", "\\U\\1\\E\\2\\U\\3", txt2, perl=TRUE)
 sub("(\\w)(\\w*)(\\w)", "\\U\\1\\E\\2\\U\\3", txt2, perl=TRUE)

## named capture
notables <- c("  Ben Franklin and Jefferson Davis",
              "\tMillard Fillmore")
# name groups 'first' and 'last'
name.rex <- "(?<first>[[:upper:]][[:lower:]]+) (?<last>[[:upper:]][[:lower:]]+)"
(parsed <- regexpr(name.rex, notables, perl = TRUE))
gregexpr(name.rex, notables, perl = TRUE)[[2]]
parse.one <- function(res, result) {
  m <- do.call(rbind, lapply(seq_along(res), function(i) {
    if(result[i] == -1) return("")
    st <- attr(result, "capture.start")[i, ]
    substring(res[i], st, st + attr(result, "capture.length")[i, ] - 1)
  }))
  colnames(m) <- attr(result, "capture.names")
  m
}
parse.one(notables, parsed)

## Decompose a URL into its components.
## Example by LT (http://www.cs.uiowa.edu/~luke/R/regexp.html).
x <- "http://stat.umn.edu:80/xyz"
m <- regexec("^(([^:]+)://)?([^:/]+)(:([0-9]+))?(/.*)", x)
m
regmatches(x, m)
## Element 3 is the protocol, 4 is the host, 6 is the port, and 7
## is the path.  We can use this to make a function for extracting the
## parts of a URL:
URL_parts <- function(x) {
    m <- regexec("^(([^:]+)://)?([^:/]+)(:([0-9]+))?(/.*)", x)
    parts <- do.call(rbind,
                     lapply(regmatches(x, m), `[`, c(3L, 4L, 6L, 7L)))
    colnames(parts) <- c("protocol","host","port","path")
    parts
}
URL_parts(x)

## There is no gregexec() yet, but one can emulate it by running
## regexec() on the regmatches obtained via gregexpr().  E.g.:
pattern <- "([[:alpha:]]+)([[:digit:]]+)"
s <- "Test: A1 BC23 DEF456"
lapply(regmatches(s, gregexpr(pattern, s)),
       function(e) regmatches(e, regexec(pattern, e)))
# }

See Also

regular expression (aka regexp) for the details of the pattern specification. regmatches for extracting matched substrings based on the results of regexpr gregexpr and regexec. glob2rx to turn wildcard matches into regular expressions. agrep for approximate matching. charmatch pmatch for partial matching match for matching to whole strings startsWith for matching of initial parts of strings. tolower toupper and chartr for character translations. apropos uses regexps and has more examples. grepRaw for matching raw vectors. Options PCRE_limit_recursion PCRE_study and PCRE_use_JIT. extSoftVersion for the versions of regex and PCRE libraries in use pcre_config for more details for PCRE.