【问题标题】:regex for capture groups捕获组的正则表达式
【发布时间】:2021-06-01 14:23:34
【问题描述】:

我还在学习正则表达式。我正在尝试为strcapture 捕获下面() 中的组。在下面的文本中定义两个捕获组的正则表达式的任何帮助表示赞赏!

示例 1

1. 4301 TMA_Scan1_Core[1,1,A]_[10844,40623]_component_data.tif - resolution #1

捕捉:

1. (4301) TMA_Scan1_Core[1,(1,A)]_[10844,40623]_component_data.tif - resolution #1

示例 2

3. TMA A_Scan1_Core[1,1,A]_[4600,36783]_component_data.tif - resolution #1

捕捉:

3. (TMA A)_Scan1_Core[1,(1,A)]_[4600,36783]_component_data.tif - resolution #1

可能需要两种不同的模式来区分示例 1 和示例 2?

dput(test)
structure(list(Image = c("1. 4301 TMA_Scan1_Core[1,1,A]_[10844,40623]_component_data.tif - resolution #1", 
"2. 4302 TMA_Scan1_Core[1,6,B]_[12511,47333]_component_data.tif - resolution #1", 
"3. TMA A_Scan1_Core[1,1,A]_[4600,36783]_component_data.tif - resolution #1", 
"4. TMA B_Scan1_Core[1,9,E]_[12695,54120]_component_data.tif - resolution #1"
)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-4L), spec = structure(list(cols = list(Image = structure(list(), class = c("collector_character", 
"collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), skip = 1L), class = "col_spec"))

将下面的“模式”替换为将第 1 组和第 2 组捕获到“文件”和“ID”中

out <- strcapture("pattern", test$Image, list("File" = "", "ID" = ""))

得到:

out<- as.data.frame("File"= c("4301","4302", "TMA A", "TMA B"), "ID" = c("1A","6B","1A","9E"))

【问题讨论】:

  • 请说明进行这些替换的确切规则。另外,请包含您已经尝试过的任何代码。

标签: r regex


【解决方案1】:

您可以尝试以下方法:

strcapture('\\d+\\.\\s(\\w+)(\\s[A-Z]).*\\[\\d+,(\\d+,[A-Z])', test$Image, 
           list("File1" = "", "File2" = "", "ID" = "")) %>%
  dplyr::mutate(File2 = replace(File2, grepl('^\\d+$', File1), NA), 
                ID = sub(',', '', ID)) %>%
  tidyr::unite(File, File1, File2, na.rm = TRUE, sep = '')

#   File ID
#1  4301 1A
#2  4302 6B
#3 TMA A 1A
#4 TMA B 9E

逻辑如下:

我们在 3 列中捕获数据。

File1 - 数字和点之后的第一个单词 (\\d+\\.\\s)

File2 - 空格和一个大写字母 (\\s[A-Z])

ID - [] 内的数字和大写字母。

如果 File2 值中只有数字,我们将其替换为 NA。从 ID 列中删除逗号,并组合 File1File2 列删除 NA 值。

【讨论】:

    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多