Mohaa Mohaa - 1 year ago 96
R Question

How to extract substrings that start and end with a specific character, in a single string?

For example I have the following string:

sample = "I am a good guy; he is cool; I am a cool dude; let's do it!"

I need to find substrings which start with "I am" and end with ";" so the output should be like:

I am a good guy
I am a cool dude

Any suggestions how to do this in R? Thanks

Answer Source

Here is a stringr library solution:

str_match_all(sample, "I am.*?;")
#     [,1]               
#[1,] "I am a good guy;" 
#[2,] "I am a cool dude;"

stringer has several very powerful functions for dealing with splitting and extracting information from strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download