开发者

All possible sequences of given sets of characters

开发者 https://www.devze.com 2022-12-07 18:00 出处:网络
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,

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

精彩评论

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

关注公众号