簡體   English   中英

你如何在R中提取兩個字符之間的值?

[英]how do you extract values between two characters in R?

我正在嘗試使用正則表達式從 R 中的這個字符串中提取服務器名稱(server101):

@和下一個句點 (.)之間的值

t<-c("Current CPU load - jvm machine[example network-app_svc_group_mem4]@server101.example.com")

我試過這個:

gsub('.*\\@(\\d+),(\\d+).*', '\\1', t)

這似乎不起作用,有什么想法嗎?

由於您只期待一場比賽,您可以在這里使用一個簡單的sub

t <- "Current CPU load - jvm machine[example network-app_svc_group_mem4]@server101.example.com"
sub(".*@([^.]+)\\..*", "\\1", t)
##  => [1] "server101"

在線查看R 演示

細節

  • .* - 任何 0+ 個字符,盡可能多
  • @ - 一個@字符
  • ([^.]+) - 第 1 組( "\\\\1" ):
  • \\\\. - 一個點(你需要轉義的其他字符是$ , ^ , * , ( , ) , + , [ , \\ , ?
  • .* - 任何 0+ 個字符,盡可能多

這里有一些替代方案。

您可以使用以下基本 R 代碼來提取 1+ 個字符,而不是. ( [^.]+ ) 在第一個@

> t <- "Current CPU load - jvm machine[example network-app_svc_group_mem4]@server101.example.com"
> pattern="@([^.]+)"
> m <- regmatches(t,regexec(pattern,t))
> result = unlist(m)[2]
> result
[1] "server101"

使用regexec ,您可以訪問子regexec (捕獲組內容)。

查看在線 R 演示

另一種方法是將regmatches / regexpr與 PCRE 正則表達式一起使用,帶有(?<=@)后視,僅檢查字符是否存在,但不會將字符放入匹配中:

> result2 <- regmatches(t, regexpr("(?<=@)[^.]+", t, perl=TRUE))
> result2
[1] "server101"

一個干凈的stringr方法是使用與str_extract相同的 PCRE 正則表達式(使用類似的(因為它也支持環視)、ICU、正則表達式風格):

> library(stringr)
> t<-c("Current CPU load - jvm machine[example network-app_svc_group_mem4]@server101.example.com")
> str_extract(t, "(?<=@)[^.]+")
[1] "server101"

與字符串:

library(stringr)
str_match(t, ".*@([^\\.]*)\\..*")[2]
#[1] "server101"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM