Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything after a character, but keep the character

Tags:

regex

r

Let's say I have a string that reads "45216 Walnut Avenue Mary's Bake Shop". I want to remove everything after the word Avenue, but I would like avenue to remain. How does this work?

I've tried the following with no luck:

a <- "45216 Walnut Avenue Mary's Bake Shop"
a <- gsub("Avenue.*$", "", a)

[1] "45216 Walnut "
like image 875
JennJain Avatar asked Nov 14 '17 22:11

JennJain


People also ask

How do you delete everything after a certain character?

Press Ctrl + H to open the Find and Replace dialog. In the Find what box, enter one of the following combinations: To eliminate text before a given character, type the character preceded by an asterisk (*char). To remove text after a certain character, type the character followed by an asterisk (char*).

How do I remove all characters from a string after a specific character?

To remove everything after a specific character in a string:Use the String. split() method to split the string on the character. Access the array at index 0 . The first element in the array will be the part of the string before the specified character.

How do I extract text before and after a specific character in Excel?

Extract text before or after space with formula in Excel Select a blank cell, and type this formula =LEFT(A1,(FIND(" ",A1,1)-1)) (A1 is the first cell of the list you want to extract text) , and press Enter button.


1 Answers

Probably the most direct way to do this would be by capturing "Avenue" with () and then chopping off everything that appears after it:

a <- "45216 Walnut Avenue Mary's Bake Shop"
gsub("(Avenue).*", "\\1", a)

You'll get:

## [1] "45216 Walnut Avenue"
like image 167
lefft Avatar answered Sep 30 '22 20:09

lefft