Reputation: 625
I want to substring the below words in R till it finds a numeric character.
BARCLAYS BANK PLC 6.860
The answer should be
BARCLAYS BANK PLC
I tired to used substr but I am not sure how to remove the numeric variables.
Upvotes: 1
Views: 348
Reputation: 887481
We can use sub
to match one or more space (\\s+
) followed by numbers till the end of the string ($
) (this is based on the example provided), and replace by ''
.
sub("\\s+[0-9.]+$", '', str1)
#[1] "BARCLAYS BANK PLC" "US TREASURY" "NEW BRUNSWICK"
Or using the OP's description (to keep only characters till a numeric character is found), we match all non-numeric characters from the beginning of the string (^
), keep it in a capture group and replace with the backreference (\\1
).
sub("^([^0-9.]+)\\s+.*", '\\1', str1)
#[1] "BARCLAYS BANK PLC" "US TREASURY" "NEW BRUNSWICK"
str1 <- c("BARCLAYS BANK PLC 6.860", "US TREASURY 2.500",
"NEW BRUNSWICK 4.800")
Upvotes: 1