Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ruby查找字符串中出现的所有1或2个字母_Ruby_Regex - Fatal编程技术网

使用ruby查找字符串中出现的所有1或2个字母

使用ruby查找字符串中出现的所有1或2个字母,ruby,regex,Ruby,Regex,如果我有一个字符串,如“abcde”,并且我想得到一个二维数组,所有组合1或2个字母 [ ['a', 'b', 'c', 'd', 'e'], ['ab', 'c', 'de'], ['a', 'bc', 'd', 'e'] ... 我该怎么做呢 我想用ruby做这个,我想我应该使用正则表达式。我试过使用 strn = 'abcde' strn.scan(/[a-z][a-z]/) 但这只会给我两个字符的不同集合 ['ab', 'cd'] 不,这里不适合正则表达式。确定您可以匹配一个或两个

如果我有一个字符串,如“abcde”,并且我想得到一个二维数组,所有组合1或2个字母

[ ['a', 'b', 'c', 'd', 'e'], ['ab', 'c', 'de'], ['a', 'bc', 'd', 'e'] ...
我该怎么做呢

我想用ruby做这个,我想我应该使用正则表达式。我试过使用

strn = 'abcde'
strn.scan(/[a-z][a-z]/)
但这只会给我两个字符的不同集合

['ab', 'cd']

不,这里不适合正则表达式。确定您可以匹配一个或两个字符,如下所示:

strn.scan(/[a-z][a-z]?/)
# matches: ['ab', 'cd', 'e']
但是您不能使用正则表达式生成所有组合的(2d)列表。

我认为应该这样做(尚未测试):

def查找字母组合(str)
如果str.empty返回[[]]?
组合=[]
查找字母组合(str[1..-1])。每个字母都是c|

组合正则表达式对这类问题没有帮助。我建议在Ruby 1.9中使用handy:

def每个字母和字母对
字母=s.split(“”)
字母.组合(1).至字母a+字母.组合(2).至字母a
结束
ss=每个字母和字母对(“abcde”)
学生必须遵守以下规则:“[“a”]、[“b”]、[“c”]、[“d”]、[“e”]、[“a”、“b”]、[“a”、“d”]、[“a”、“e”]、[“b”、“c”]、[“b”、“d”]、[“b”、“e”]、[“c”、“d”]、[“c”、“e”]、[“d”、“e”]、[“d”]

函数递归方法:

def get_combinations(xs, lengths)
  return [[]] if xs.empty?
  lengths.take(xs.size).flat_map do |n|
    get_combinations(xs.drop(n), lengths).map { |ys| [xs.take(n).join] + ys } 
  end
end

get_combinations("abcde".chars.to_a, [1, 2])
#=> [["a", "b", "c", "d", "e"], ["a", "b", "c", "de"], 
#    ["a", "b", "cd", "e"], ["a", "bc", "d", "e"], 
#    ["a", "bc", "de"], ["ab", "c", "d", "e"], 
#    ["ab", "c", "de"], ["ab", "cd", "e"]]

为什么它是二维阵列?也就是说,是什么导致一个项目出现在一个子数组中,而不是另一个子数组中?对不起,应该更具体一些。查看带有子数组的数组的输出。每个子数组包含原始字符串的所有字符,这些字符分为1个或2个字符的子字符串。如何确定子字符串是一个字符还是两个字符?它们是随机决定的吗?你指的是序列,而不是组合。显然,使用数组#组合可能会使解决方案受益,但OP想要的不是还有很长的路要走吗?@tokland:是的,解析正则表达式可能有一个解决方案(假设它受到确定性的约束)生成所有可能的匹配字符串,但解决方案似乎相当复杂。另外,我是lazy=)请注意,这种与数学相关的算法往往会受到命令式方法冗长的影响。递归似乎更合适。
def get_combinations(xs, lengths)
  return [[]] if xs.empty?
  lengths.take(xs.size).flat_map do |n|
    get_combinations(xs.drop(n), lengths).map { |ys| [xs.take(n).join] + ys } 
  end
end

get_combinations("abcde".chars.to_a, [1, 2])
#=> [["a", "b", "c", "d", "e"], ["a", "b", "c", "de"], 
#    ["a", "b", "cd", "e"], ["a", "bc", "d", "e"], 
#    ["a", "bc", "de"], ["ab", "c", "d", "e"], 
#    ["ab", "c", "de"], ["ab", "cd", "e"]]