[R] regular expression for nth character in a string

jim holtman jholtman at gmail.com
Mon Apr 25 12:37:12 CEST 2011


will this do it:


> x <- "InTrouble"
> sub("^(..).*", "\\1", x)  # first two
[1] "In"
> sub(".*(...)$", "\\1", x)  # last three
[1] "ble"
> sub("^..(...).*", "\\1", x)  # 3rd,4th,5th char
[1] "Tro"
>


2011/4/25 Gonçalo Ferraz <gferraz29 at gmail.com>:
> Hi, I have a string
>
> "InTrouble"
>
> and want to extract, say, the first two characters: "In"
> or the last three: "blee"
> or the 3rd, 4th, and 5th: "Trou"
>
> Is there an easy way of doing this quickly with regular expressions in gsub, grep or similar?
>
> Thank you for any help.
>
> Gonçalo
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list