Selecting Variable Length Strings Among Multiple Strings in R

Viewed 82

I need a function or more likely a regex script that will allow me to pick out text strings based on a condition.

Example:

Input <- c("Red1 Orange", "Yellow Green2", "Blue3 Violet")

Leads to: "Red1", "Green2", "Blue3"

I have tried variety of options including:

str_extract(NamesCor, "[a-z][a-z][a-z][a-z][0-9]|
            [a-z][a-z][a-z][0-9]|
            [a-z][a-z][0-9]")

Which returns reen2, blue3

3 Answers

You may use

stringr::str_extract(Input, "\\b[A-Za-z]+\\d+\\b")
stringr::str_extract(Input, "\\b\\p{L}+\\d+\\b")   # A Unicode aware version

See R demo:

Input <- c("Red1 Orange", "Yellow Green2", "Blue3 Violet")
library(stringr)
str_extract(Input, "\\b[A-Za-z]+\\d+\\b")
## [1] "Red1"   "Green2" "Blue3" 

See also the regex demo. Details:

  • \b - a word boundary
  • [A-Za-z]+ - 1+ ASCII letters (\p{L} matches any Unicode letter)
  • \d+ - 1+ digits
  • \b - a word boundary

in Base R.

 gsub(".*?([0-9]\\w+|\\w+[0-9]).*","\\1",Input)
   [1] "Red1"   "Green2" "Blue3" 

or

gsub(".*?(\\d\\w+|\\w+\\d).*","\\1",Input)
   [1] "Red1"   "Green2" "Blue3" 

I like to use this cheat sheet for regular expressions in R

Using sub in base R :

sub('.*?([A-Za-z]+\\d+).*', '\\1', Input)
#[1] "Red1"   "Green2" "Blue3" 

This captures characters followed by numbers.

Related