简体   繁体   中英

R: Extract substring and paste the same substring at the end of a string

I have some strings with the following pattern of: letters and numbers

A11B3XyC4 
A1B14C23XyC16 
B14C23XyC16D3

I want to extract the part "Xy" (always the same letters) and paste it at the end of the remaining string. The result schould look like this:

A11B3C4. Xy
A1B14C23C16. Xy
B14C23C16D3. Xy

Could you point me to a function capable of this?

Thank you!

We can use sub and build groups in the pattern argument by wrapping them in () . We can access these groups in the replacement argument with \\ followed by the group number.

strs <- c("A11B3XyC4", 
  "A1B14C23XyC16",
  "B14C23XyC16D3")

sub("(.*)(Xy)(.*)", "\\1\\3\\. \\2", strs)
#> [1] "A11B3C4. Xy"     "A1B14C23C16. Xy" "B14C23C16D3. Xy"

Created on 2021-08-27 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM