Aqqi
Aqqi

Reputation: 125

Extract weekdays present in string in r

I want to extract weekdays present in string into a list. Appreciate if some one could suggest the easy way out.

strg <- 'Consumer   bot  --At 08:00 PM, only on Monday, Tuesday, Wednesday, Thursday, and Friday'

Expecting result to be in list like: "Monday" "Tuesday" "Wednesday" "Thursday" "Friday"

Upvotes: 1

Views: 60

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389265

We can also generate all days of the week and then extract the ones that match pattern.

stringr::str_extract_all(strg, paste0(weekdays(Sys.Date()+0:6),collapse = "|"))[[1]]
#[1] "Monday"    "Tuesday"   "Wednesday" "Thursday"  "Friday" 

paste0 generates all days.

paste0(weekdays(Sys.Date()+0:6), collapse = "|") 
#[1] "Thursday|Friday|Saturday|Sunday|Monday|Tuesday|Wednesday" 

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522712

We can try matching all occurrences of the following pattern:

\b\w+day\b

Sample script:

strg <- 'Consumer   bot  --At 08:00 PM, only on Monday, Tuesday, Wednesday, Thursday, and Friday'
m <- gregexpr("\\b\\w+day\\b", strg)
regmatches(strg, m)[[1]]

[1] "Monday"    "Tuesday"   "Wednesday" "Thursday"  "Friday"   

We could try to make the pattern more restrictive, to avoid unwanted matches such as holiday:

\b(?:Mon|Tues|Wed|Thurs|Fri|Sat|Sun)day\b

But for your sample data, the above pattern would generate the same result.

Upvotes: 2

Related Questions