user1471980
user1471980

Reputation: 10636

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?

Upvotes: 0

Views: 63

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269854

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 @:

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.

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:

gsub("^.*- |@.*", "", node)
## [1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"

Upvotes: 1

Sotos
Sotos

Reputation: 51592

A couple of ideas here,

1) Using regmatches as shown here, i.e

regmatches(node,gregexpr("(?<=-\\s).*?(?=@)", node, perl=TRUE))

2) Using the fun function word from stringr, i.e.

stringr::word(node, 2, sep = ' - |@')

Both resulting in

[1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"

Upvotes: 1

akrun
akrun

Reputation: 887431

We can use gsub to match zero or more characters until a - followed by space or | 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

library(stringr)
str_extract(node, "(?<=-\\s)[^@]+")
#[1] "UAT_jvm1[mainnetwork-cmod_svc_group_mem1]"

data

node <- c("Current CPU load - UAT_jvm1[mainnetwork-cmod_svc_group_mem1]@tt11")

Upvotes: 1

Related Questions