You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby与Python正则正向预查差异问题求助(Advent of Code场景)

关于Ruby与Python中正向预查正则行为差异的问题(Advent of Code 2023 Day1 Part2)

我刚开始参与2023年Advent of Code,借此学习新编程语言。我有一定Python基础,今天刚安装Ruby。在Day1 Part2中,需要匹配数字及其拼写形式:

  • Python中使用带正向预查的正则(?=(0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine))能得到正确结果,但Ruby中使用该正则返回nil;
  • 使用无预查的正则0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine时,两者匹配结果一致,但最终答案错误。

想了解正向预查在Ruby和Python中的行为差异原因。

Python代码

import re

input = open("../resources/input.txt","r")
lines = input.readlines()

targets = [
    '0','1','2','3','4','5','6','7','8','9',
    'zero','one','two','three','four','five','six','seven','eight','nine'
]
values = {
    '0': 0,
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9,
    'zero': 0,
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4,
    'five': 5,
    'six': 6,
    'seven': 7,
    'eight': 8,
    'nine': 9
}

sum = 0

for line in lines:
    numbers = re.findall(r"(?=("+'|'.join(targets)+r"))", line)

    firstDigitValue = values[numbers[0]] * 10
    lastDigitValue = values[numbers[-1]]

    sum += (firstDigitValue+lastDigitValue)

print(sum)

Ruby代码

# Init vars
sum = 0

reg = /\d|zero|one|two|three|four|five|six|seven|eight|nine/
reg2 = /(?=(0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine))/
reg3 = /0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine/

values = {
    '0' => 0,
    '1' => 1,
    '2' => 2,
    '3' => 3,
    '4' => 4,
    '5' => 5,
    '6' => 6,
    '7' => 7,
    '8' => 8,
    '9' => 9,
    'zero' => 0,
    'one' => 1,
    'two' => 2,
    'three' => 3,
    'four' => 4,
    'five' => 5,
    'six' => 6,
    'seven' => 7,
    'eight' => 8,
    'nine' => 9
}

# Pipe the file line by line and do per line
File.foreach("../resources/input.txt", chomp: true) do |line|
    # Get the first and last digits as their values
    numbers = line.scan(reg3)

    firstDigitValue = values[numbers[0]] * 10
    lastDigitValue = values[numbers[-1]]

    # accumulate
    sum += (firstDigitValue+lastDigitValue)

end

puts sum

内容的提问来源于stack exchange,提问作者jcodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:25:05