R/subfield_extractor.R

Defines functions subfield_extractor

Documented in subfield_extractor

#' Extract specific subfield from a single field content string.
#'
#' @param single_string A string.
#' @param subfield_name A string, started with "$".
#' @examples
#' subfield_extractor("##$aЦУНБ Москва$bабонемент$p2000004575793$x798717-3$92040.00$h84.4Шве$iЛ 14", "$x)
#' subfield_extractor("##$a5-88215-748-X$910 000", "$a)

subfield_extractor <- function(single_string, subfield_name) {
  if (str_detect(single_string, fixed(subfield_name))) {
    start_of_sub <- str_locate_all(single_string, fixed(subfield_name))[[1]][, 1]
    n_subs <- length(start_of_sub)
    res <- str_sub(single_string, start_of_sub + 2, rep(-1, n_subs))
    end_of_sub <- lapply(
      res,
      function(x) {
        if (str_detect(x, fixed("$"))) {
          end <- str_locate(x, fixed("$"))[1, 1] - 1
        } else {
          end <- -1
        }
        return(end)
      }
    ) %>% unlist()
    res <- str_sub(res, 1, end_of_sub)
  } else {
    res <- NULL
  }
  return(res)
}
Volodin-DD/rusmarcFunds documentation built on Oct. 31, 2019, 1:11 a.m.