Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim all words in string above given length?

Tags:

regex

r

For example this matches every word of length 3 or more, and replaces it with xx:

library(stringr)
str_replace_all(c("This is a long", "Another one."), "([a-zA-Z]{3,})", "xx")
#output: "xx is a xx" "xx xx"

What I'd like to get is:

#"Thi is a lon" "Ano one."
like image 748
enedene Avatar asked Sep 27 '22 20:09

enedene


1 Answers

You can use the following to match:

([a-zA-Z]{3})[a-zA-Z]+

And replace with \\1

You can also use gsub (from comments)

gsub("([a-zA-Z]{3})[a-zA-Z]+", "\\1", c("This is a long", "Another one."))
like image 198
karthik manchala Avatar answered Nov 07 '22 01:11

karthik manchala