简体   繁体   中英

R - Use regex to remove all strings, special characters, and pattern ending element

Say I have a character vector ids as follows:

ids <- c("367025001", "CT_341796001", "M13X01692-01", "13C025050901", "13C00699551")

I want to search each element and remove all letters, all special characters, and "01" when it ends the element. So ids would become:

ids_replaced <- c("3670250", "3417960", "1301692", "130250509", "1300699551")

I'm coming out somewhat close, but it hasn't worked as I've intended it to.

gsub("(.*?)(\\d+?)(01$)", "\\2", ids, perl = TRUE)

You could use

gsub("01$|\\D", "", ids)
# [1] "3670250"    "3417960"    "1301692"    "130250509"  "1300699551"
identical(gsub("01$|\\D", "", ids), ids_replaced)
# [1] TRUE

Regular Expression Explanation:

  • 01 matches "01"
  • $ before an optional \\n , and the end of the string
  • | OR
  • \\D matches non-digits (all but 0-9)

Using rex may make this type of task a little simpler.

ids <- c("367025001", "CT_341796001", "M13X01692-01", "13C025050901", "13C00699551")

re_substitutes(ids,
  rex(non_digits %or% list("01", end)),
  '',
  global = TRUE)

#> [1] "3670250"    "3417960"    "1301692"    "130250509"  "1300699551"

I'm not sure how to do it in R but you can use this regex:

-\d+$|\D

Working demo

在此输入图像描述

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