0

How to convert the following string in R :

this_isastring_12(=32)

so that only the following is kept

isastring_12

Eg

f('this_isastring_12(=32)') returns 'isastring_12'

This should work on other strings with a similar structure, but different characters

Another example with a different string of similar structure

f('something_here_3(=1)') returns 'here_3'
7
  • What is the logic of conversion ? Keep everything after....? Or remove everything after.. ?Or something else ? Commented Oct 8, 2019 at 4:23
  • @RonakShah to keep the part highlighted Commented Oct 8, 2019 at 4:26
  • so sub(".*(isastring_12).*", "\\1", "this_isastring_12(=32)") would work ? Commented Oct 8, 2019 at 4:27
  • yes but it wouldn't generalise, I guess if the parens were (.*?) it might work? Commented Oct 8, 2019 at 4:28
  • that is what I mean when I asked you for the logic of conversion ? Do you want to keep everything after first underscore till an opening bracket is found or is there some other logic involved ? Commented Oct 8, 2019 at 4:30

2 Answers 2

1

We can use sub to extract everything from first underscore to opening round bracket in the text.

sub(".*?_(.*)\\(.*", "\\1", x)
#[1] "isastring_12" "here_3"       "string_4"    

where x is

x <- c("this_isastring_12(=32)", "something_here_3(=1)", "another_string_4(=1)")
Sign up to request clarification or add additional context in comments.

Comments

1

You could use the package unglue.

Borrowing Ronak's data :

x <- c("this_isastring_12(=32)", "something_here_3(=1)", "another_string_4(=1)")
library(unglue)
unglue_vec(x, "{=.*?}_{res}({=.*?})")
#> [1] "isastring_12" "here_3"       "string_4" 
  • {=.*?} matches anything until what's next is matched, but doesn't extract anything because there's no lhs to the equality
  • {res}, where the name res could be replaced by anything, matches anything, and extracts it
  • outside of curly braces, no need to escape characters
  • unglue_vec() returns an atomic vector of the matches

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.