Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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)

out

[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

Browse Categories

...