['abcd', '4567'] 尝试通过正则表达式执行此操作,但代码看起来要长得多: (?!a-6ren">
gpt4 book ai didi

ruby - 检查字符串在 Ruby on Rails 中是否有顺序字符

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:40 24 4
gpt4 key购买 nike

尝试验证一个字符串以查明它是否包含 3 个或更多的连续字符。

例子:

"11abcd$4567" => ['abcd', '4567']

尝试通过正则表达式执行此操作,但代码看起来要长得多:

(?!abc|bcd|cde|.....)

有没有一种简单的方法可以通过正则表达式或普通 ruby​​ 检查连续字符?

最佳答案

正则表达式在这里不合适。它们不够灵活,无法构建一般情况; Unicode 非常庞大,构建一个响应任何升序字符序列的正则表达式需要列出数万或数十万个案例中的每一个。它可以通过编程方式完成,但这需要时间,而且在内存方面会非常昂贵。

def find_streaks(string, min_length=3)
string # "xabcy"
.each_char # ['x', 'a', 'b', 'c', 'y']
.chunk_while { |a, b| a.succ == b } # [['x'], ['a', 'b', 'c'], ['y']]
.select { |c| c.size >= min_length } # [['a', 'b', 'c']]
.map(&:join) # ['abc']
end

我想这可能会作为一个 polyfill 起作用……试试看吧?

                                         # skip this thing on Ruby 2.3+, unneeded
unless Enumerable.instance_methods.include?(:chunk_while)
module Enumerable
def chunk_while # let's polyfill!
streak = nil # twofold purpose: init `streak` outside
# the block, and `nil` as flag to spot
# the first element.

Enumerator.new do |y| # `chunk_while` returns an `Enumerator`.
each do |element| # go through all the elements.
if streak # except on first element:
if yield streak[-1], element # give the previous element and current
# one to the comparator block.
# `streak` will always have an element.
streak << element # if the two elements are "similar",
# add this one to the streak;
else # otherwise
y.yield streak # output the current streak and
streak = [element] # start a new one with the current element.
end
else # for the first element, nothing to compare
streak = [element] # so just start the streak.
end
end
y.yield streak if streak # output the last streak;
# but if `streak` is `nil`, there were
# no elements, so no output.
end
end
end
end

好吧,笨蛋。在这里,我将手写所有这些……本来可以这么简单:

unless Enumerable.instance_methods.include?(:chunk_while)
module Enumerable
def chunk_while
slice_when { |a, b| !yield a, b }
end
end
end

是的,chunk_while 正好与 slice_when 相反。甚至可以在原始代码中替换它,如 .slice_when { |a, b| a.succ != b .有时我很慢。

关于ruby - 检查字符串在 Ruby on Rails 中是否有顺序字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40903801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com