Ruby 如何提取字符串中所有'the'及其后跟随的关联内容
Ruby 独立"the"单词及后续关联词提取实现
针对给定测试字符串的提取需求,有两类可直接落地的实现思路:
方案1:正则全局匹配(代码量最少)
直接通过正则定位符合要求的内容,无需拆分整个字符串做遍历,执行效率更高。
test_str = "the horse and the hound and the horn that belonged to" # 正则逻辑说明: # \b 匹配单词边界,确保只识别独立出现的"the",不会误匹配其他单词内嵌的the # \s+ 匹配the和后续单词之间的任意长度空白 # (\w+) 捕获the后面紧跟的第一个连续单词 matches = test_str.scan(/\bthe\s+(\w+)/) result = matches.map { |word_pair| "the #{word_pair[0]}" }.join(", ")
运行上述代码后,result的输出值正好是目标格式the horse, the hound, the horn。
方案2:拆分单词遍历(可读性最强)
适合不熟悉正则语法的场景,逻辑完全透明,排查问题时定位更方便。
test_str = "the horse and the hound and the horn that belonged to" word_list = test_str.split extracted_items = [] # 逐位置遍历单词,遇到值为"the"的位置,取紧邻的下一个单词拼接入结果 word_list.each_with_index do |current_word, pos| adjacent_word = word_list[pos + 1] extracted_items << "the #{adjacent_word}" if current_word == "the" && adjacent_word end result = extracted_items.join(", ")
常见踩坑提醒
- 使用正则方案时不要省略单词边界判断:如果去掉
\b,遇到类似there、other这类内嵌"the"的单词时会出现误匹配。 - 两种实现都默认"the"和后续关联词之间为空白分隔,如果实际文本存在标点分隔的场景,可根据真实格式调整匹配规则即可。
内容的提问来源于stack exchange,提问作者Dedy Puji
相关产品推荐
相关产品推荐

