1

I am trying to extract some keywords from a string in R as follows.

I want to get the strings in between the first ":" after each "[" and ", " or "\b".

string <- c("[G1]3451:GHEIN, [G2]FR343:4453, [G05]RT3342:34:GR", "[L1]TTG4:4532, [L3]EK445:GHR[1C]", "[RT1]JGR:45,RE")

gsub('\\[\\S+:', '', string)
"GHEIN, 4453, GR" "4532, GHR[1C]"   "45,RE"

The problem is when two ":" are there. I should be getting the output as 34:GR instead of GR.

out <- c("GHEIN, 4453, 34:GR", "4532, GHR[1C]", "45,RE")

How to get the desired result using regex in R?

1 Answer 1

4

Make it non-greedy:

gsub('*?\\[\\S+:', '', string)
[1] "GHEIN, 4453, 34:GR" "4532, GHR[1C]"      "45,RE"      
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.