gpt4 book ai didi

Ruby String#scan 相当于返回 MatchData

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:18 24 4
gpt4 key购买 nike

正如问题标题中所述,Ruby 字符串上是否有等效于 String#Scan 的方法?但不是只返回每个匹配项的列表,而是返回一个 MatchData 数组?例如:

# Matches a set of characters between underscore pairs
"foo _bar_ _baz_ hashbang".some_method(/_[^_]+_/) #=> [#&ltMatchData "_bar_"&rt, &ltMatchData "_baz_"&rt]

或者任何我能得到相同或相似结果的方法都是好的。我想这样做是为了找到 Ruby 字符串中“字符串”的位置和范围,例如"goodbye and "world" inside "'goodbye' cruel 'world'".

最佳答案

memo = []
"foo _bar_ _baz_ hashbang".scan(/_[^_]+_/) { memo << Regexp.last_match }
=> "foo _bar_ _baz_ hashbang"
memo
=> [#<MatchData "_bar_">, #<MatchData "_baz_">]

关于Ruby String#scan 相当于返回 MatchData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9528035/

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