Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (50.2k points)

I just wanted to know how to cut all Lines after a specific set of characters in R.

Let's sat I am having the following set of characters:

documentName <- "Hello my name is Johann my had is the largest to be deleted X"

My desired outcome is:

documentName <- "Hello my name is Johann"

1 Answer

0 votes
by (108k points)

You can either capture all the content that is appearing before Johann:

x <- "Hello my name is Johann my had is the largest to be deleted"

out <- sub("^(.*\\bJohann)\\b.*$", "\\1", x)


[1] "Hello my name is Johann"

Or just strip off all characters appearing after Johann:

sub("(?<=\\bJohann)\\s+.*$", "", x, perl=TRUE)

If you are a beginner and want to know more about R then do check out the R programming course

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers


108k users

Browse Categories