gpt4 book ai didi

arrays - 检查数组中的字符串是否包含另一个数组中的子字符串

转载 作者:行者123 更新时间:2023-12-02 01:26:18 24 4
gpt4 key购买 nike

我的数组中有一个字符串:

string_array = ["<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15737c6766617b74787055717a78747c7b3b767a783b7460" rel="noreferrer noopener nofollow">[email protected]</a>", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b676a787f656a666e4b6f64666a62657f7c6425686466256a7e" rel="noreferrer noopener nofollow">[email protected]</a>"]
domains = ["@domain.com.au", "firstname"]

我需要删除上面数组中的字符串包含另一个数组中的子字符串的所有匹配项。

我尝试过以下方法:

test = string_array.reject { |item| domains.include?(item) }
#=> ["firstn<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b979fba9e95979b9394d4999597d49b8f" rel="noreferrer noopener nofollow">[email protected]</a>", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82eee3f1f6ece3efe7c2e6edefe3ebecf6f5edace1edeface3f7" rel="noreferrer noopener nofollow">[email protected]</a>"]

应该是反过来才对吧?类似的东西

test = string_array.reject { |item| item.include?(domains) }

但这会引发类型错误:没有将数组隐式转换为字符串

最佳答案

我会这样做:

string_array = ["<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="65030c1716110b04080025010a08040c0b4b060a084b0410" rel="noreferrer noopener nofollow">[email protected]</a>", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c4c9dbdcc6c9c5cde8ccc7c5c9c1c6dcdfc786cbc7c586c9dd" rel="noreferrer noopener nofollow">[email protected]</a>"]
domains = ["@domain.com.au", "firstname"]

string_array.reject { |email| domains.any? { |domain| email.include?(domain) } }
#=> ["<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf0fdefe8f2fdf1f9dcf8f3f1fdf5f2e8ebf3b2fff3f1b2fde9" rel="noreferrer noopener nofollow">[email protected]</a>"]

您的版本不起作用的原因是您将字符串与字符串数组进行了比较。并且由于数组中不包含确切的子字符串,因此不存在匹配项。相反,您必须将每个字符串与任何其他字符串的子字符串进行比较。

关于arrays - 检查数组中的字符串是否包含另一个数组中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74528996/

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