开发者

All possible sequences of given sets of characters

I have the following string:

'[ABC][abcd][XYZ]'

I want to generate all possible strings where the first character is A, B, or C, the second character is a, b, c, or d, and the third character is X, Y, or Z.

Example: 开发者_开发百科AcX, BaZ, etc.

How to do this, preferably within Tidyverse?


First splitstr the string appropriately to get a list, then using expand.grid and paste0 with do.call .

el(strsplit('[ABC][abcd][XYZ]', '[\\[|\\]]', perl=TRUE)) |>
  {\(x) x[x != '']}() |>
  sapply(strsplit, '') |>
  do.call(what=expand.grid) |>
  do.call(what=paste0)
# [1] "AaX" "BaX" "CaX" "AbX" "BbX" "CbX" "AcX" "BcX" "CcX" "AdX" "BdX" "CdX" "AaY" "BaY" "CaY" "AbY" "BbY" "CbY" "AcY" "BcY"
# [21] "CcY" "AdY" "BdY" "CdY" "AaZ" "BaZ" "CaZ" "AbZ" "BbZ" "CbZ" "AcZ" "BcZ" "CcZ" "AdZ" "BdZ" "CdZ"


A stringr solution:

library(stringr)
str_extract_all(x,"(?<=\\[).+?(?=\\])", simplify = TRUE) |>
  str_split("") |>
  expand.grid() |>
  do.call(what = paste0)

# [1] "AaX" "BaX" "CaX" "AbX" "BbX" "CbX" "AcX" "BcX" "CcX" "AdX" "BdX" "CdX" "AaY" "BaY" "CaY" "AbY" "BbY" "CbY" "AcY" "BcY"
#[21] "CcY" "AdY" "BdY" "CdY" "AaZ" "BaZ" "CaZ" "AbZ" "BbZ" "CbZ" "AcZ" "BcZ" "CcZ" "AdZ" "BdZ" "CdZ"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜