首页 > 解决方案 > Pig Latin Converter - 需要帮助找出如何查找而不是转换数字元素

问题描述

我正在编写一个将短语转换为猪拉丁语的函数。但是,如果该短语包含一个数字,则该函数需要将它们保持原样,并且我在寻找一种方法时遇到了一些问题。

我尝试过使用regmatch,gsubwhich语句,但还没有找到最好的方法。

以下是我尝试过的一些事情:

phrase <- "the 24 brown fox jumps over the lazy brown dog"

这是功能:

piglatin = function(phrase) {

  phrase2 <- tolower(phrase)
  phrase3 <- strsplit(phrase2, split=" ")[[1]]
  phrase4 <- paste(gsub("(.)(.*)", "\\2\\1ay", phrase3), collapse=" ")
  return(phrase4)

}

这是我提取数字的尝试。这需要在某处插入到函数中。

matches <- regmatches(phrase, gregexpr("[[:digit:]]+", phrase))
as.numeric(unlist(matches))

x <- gregexpr("[0-9]+", phrase)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(phrase, x)))

输入:"the 24 brown fox jumps over the lazy brown dog"

实际输出:"hetay 42ay rownbay oxfay umpsjay veroay hetay azylay rownbay ogday"

期望的输出:"hetay 24 rownbay oxfay umpsjay veroay hetay azylay rownbay ogday"

标签: rregex

解决方案


与其尝试捕获数字,不如使用几个捕获组可能更容易 - 第一个用于第一个字母,第二个用于后续字母(如果存在),第三个用于后续空白(如果存在)。

gsub("([a-zA-Z])([a-zA-Z]*)(\\s?)", "\\2\\1ay\\3", phrase)
#[1] "hetay 24 rownbay oxfay umpsjay veroay hetay azylay rownbay ogday"

推荐阅读