[英]capture string between special characters
I have this string: 我有这个字符串:
node<-c("Current CPU load - UAT_jvm1[mainnetwork-cmod_svc_group_mem1]@tt11")
I need to capture this text from it, from "- " til the "@" sign. 我需要从“-”到“ @”符号中捕获该文本。
UAT_jvm1[mainnetwork-cmod_svc_group_mem1]
I've tried this: 我已经试过了:
str_match(node, ".*\\-+s(.*?)@.*")[,2]
any ideas? 有任何想法吗?
We can use gsub
to match zero or more characters until a -
followed by space or |
我们可以使用
gsub
直到匹配零个或多个字符-
其次是空间或|
the @
followed by other characters and replace it with blank ( ""
) @
后跟其他字符,并将其替换为空白( ""
)
gsub(".*-\\s|@.*", "", node)
#[1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"
Or if we are using stringr
或者如果我们使用
stringr
library(stringr)
str_extract(node, "(?<=-\\s)[^@]+")
#[1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"
node <- c("Current CPU load - UAT_jvm1[mainnetwork-cmod_svc_group_mem1]@tt11")
A couple of ideas here, 这里有几个想法,
1) Using regmatches
as shown here , ie 1)使用
regmatches
如图这里 ,即
regmatches(node,gregexpr("(?<=-\\s).*?(?=@)", node, perl=TRUE))
2) Using the fun function word
from stringr
, ie 2)使用
stringr
的fun函数word
,即
stringr::word(node, 2, sep = ' - |@')
Both resulting in 两者都导致
[1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"
Here are some approaches. 这里有一些方法。 No packages are used.
不使用任何软件包。
1) sub Match everything to the minus space and then capture everything up to but not including the @: 1)将所有内容匹配到减号空间,然后捕获所有内容,但不包括@:
sub(".*- (.*)@.*", "\\1", node)
## [1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"
2) sub/read.table Replace the first - with an @ and then read the string picking out the second field. 2)sub / read.table将第一个-替换为@,然后读取选择第二个字段的字符串。
read.table(text = sub("-", "@", node), sep = "@", as.is = TRUE, strip.white = TRUE)[[2]]
## [1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"
3) gsub Remove everything up to the minus space and everything from @ onwards: 3)gsub删除所有减去负号的内容以及@之后的所有内容:
gsub("^.*- |@.*", "", node)
## [1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.