1

I have this vector:

jvm<-c("test - PROD_DB_APP_185b@SERVER01" ,"uat - PROD_DB_APP_SYS[1]@SERVER2")

I need to extract text until "[" or if there is no "[", then until the "@" character.

result should be

PROD_DB_APP_185b
PROD_DB_APP_SYS

I've tried something like this:

str_match(jvm, ".*\\-([^\\.]*)([.*)|(@.*)")

not working, any ides?

6
  • OR sub("(\\[.*)?@.*", "", jvm) Commented Jul 19, 2017 at 19:05
  • 1
    @Sotos, sorry, your answer was right, one quick modification, between "-" and "[" or "@" Commented Jul 19, 2017 at 19:06
  • 1
    I have this vector - If this were a string you could match something, using (?<=-[ ])[^\[@]+(?=[\[@]) Commented Jul 19, 2017 at 19:15
  • 1
    Try sub("^.*?\\s+-\\s+([^@[]+).*", "\\1", jvm) Commented Jul 19, 2017 at 19:16
  • 1
    Or str_extract(jvm, "(?<=- )[^@\\[]+") Commented Jul 19, 2017 at 19:21

1 Answer 1

1

A sub solution with base R:

jvm<-c("test - PROD_DB_APP_185b@SERVER01" ,"uat - PROD_DB_APP_SYS[1]@SERVER2")
sub("^.*?\\s+-\\s+([^@[]+).*", "\\1", jvm)

See the online R demo

Details:

  • ^ - start of string
  • .*? - any 0+ chars as few as possible
  • \\s+-\\s+ - a hyphen enclosed with 1 or more whitespaces
  • ([^@[]+) - capturing group 1 matching any 1 or more chars other than @ and [
  • .* - any 0+ chars, up to the end of string.

Or a stringr solution with str_extract:

str_extract(jvm, "(?<=-\\s)[^@\\[]+")

See the regex demo

Details:

  • (?<=-\\s) - a positive lookbehind that matches an empty string that is preceded with a - and a whitespace immediately to the left of the current location
  • [^@\\[]+ - 1 or more chars other than @ and [.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.