Regular Expression in R with grep

I'm struggling with regular expressions again, so I would be happy if anyone can help.

I need to extract strings from some patterns:

1) "b[(Intercept) Subject:352]", where Subject:352 is the random pattern I want to get.

2) "b[Days Subject:369]", where Days and Subject:369 are random patterns, and I want to get the both matches, Days and Subject:369.

3) "r_Subject.369.Days.", where Subject.369 and .Days. are random patterns, and I want to get Subject.369 and Days (w/o dots).

what are the related regex-pattern to use with grep() or similar?

1 answer

  • answered 2017-10-11 10:39 Thierry

    1. gsub("b\\[\\(Intercept\\) (.*)\\]", "\\1", "b[(Intercept) Subject:352]")
    2. gsub("b\\[(.*) (.*)\\]", "\\1", "b[Days Subject:369]") and gsub("b\\[(.*) (.*)\\]", "\\2", "b[Days Subject:369]")
    3. gsub("r_(.*)\\.(.*)\\.", "\\1", "r_Subject.369.Days.") and gsub("r_(.*)\\.(.*)\\.", "\\2", "r_Subject.369.Days.")