简体   繁体   中英

Extract text between two strings

How can I extract text between two strings.

For eg:

x <- "ABCDName:Mr.Praveen KumarDOB"

I want to extract Mr. Praveen Kumar .

Also, I want to extract string from starting till it encounters Name:.

Try

gsub('^[^:]+:|[A-Z]{1,}$', '', x)
#[1] "Mr.Praveen Kumar"

sub('Name.*', '', x)
#[1] "ABCD"

You may try this,

> library(stringr)
> str_extract(x, perl("Name:\\K.*?(?=[A-Z]{2,})"))
[1] "Mr.Praveen Kumar"
> str_extract_all(x, perl("Name:\\K.*?(?=[A-Z]{2,})|.*?(?=Name:)"))[[1]]
[1] "ABCD"             "Mr.Praveen Kumar"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM