gpt4 book ai didi

Ruby 正则表达式忽略第一个有效(?)匹配

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:42 27 4
gpt4 key购买 nike

我正在尝试操作 SRT 字幕文件。文件开头的示例字符串 @data:

1
00:01:09,611 --> 00:01:12,404
In co-production with

2
00:01:14,783 --> 00:01:17,034
presents

我用正则表达式匹配所有 id:

@data.scan(/^\d+\w*$/)

然而,这忽略了第一个 1,只输出 2..900。我以为我在正则表达式中遗漏了一些字符,并分析了@data:

puts @data[0,10].inspect => "1\n00:01:09,611 --> "

我不明白为什么第一个 1 不匹配。同样使用 @data.match() 运行它不会产生 1 但会产生 2

然后我在 1 之前添加了一个 \n,它起作用了。但是,我不明白为什么 ^ 需要 \n 而不是字符串的真正开头。

最佳答案

如果问题出在文档中的 BOM,Ruby 支持在读取文件时检查 BOM 以及使用多字节编码。来自 IO.new 的“IO 编码”文档:

If “BOM|UTF-8”, “BOM|UTF-16LE” or “BOM|UTF16-BE” are used, ruby checks for a Unicode BOM in the input document to help determine the encoding. For UTF-16 encodings the file open mode must be binary. When present, the BOM is stripped and the external encoding from the BOM is used. When the BOM is missing the given Unicode encoding is used as ext_enc. (The BOM-set encoding option is case insensitive, so “bom|utf-8” is also valid.)

关于Ruby 正则表达式忽略第一个有效(?)匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16132577/

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