gpt4 book ai didi

Ruby 正则表达式帮助

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

我正在尝试使用 Ruby 中的正则表达式解析模式。模式是这样的,

<number>? <comma>? <number>? <term>*

哪里:

  • number 是一位或多位数字
  • 逗号","
  • term 的格式为 [.*][^.*]

我正在尝试捕捉数字和所有术语。为了澄清,这里有一些有效模式的例子:

5,50[foo,bar]
5,[foo][^apples]
10,100[baseball][^basketball][^golf]
,55[coke][pepsi][^drpepper][somethingElse]

首先,我想捕获 550[foo,bar]在第二个中,我想捕获 5[foo][^apples] 等等。

我想到的模式是:

/(\d+)?,?(\d+)?(\[\^?[^\]]+\])+/

但这只匹配数字和最后一项。如果我删除末尾的 +,那么它只会匹配第一个词。

最佳答案

我能想到的最简单的解决方案可能是通过包围组和已经存在的 + 来添加一个额外的捕获组,即

/(\d+)?,?(\d+)?((\[\^?[^\]]+\])+)/

此外,您可以通过 (\d*) 而不是 (\d+)? 来简化 \d 表达式。 ..

编辑

下面是用于测试上述建议的代码:

matches = [ "5,50[foo,bar]",
"5,[foo][^apples]",
"10,100[baseball][^basketball][^golf]",
",55[coke][pepsi][^drpepper][somethingElse]"
]

re = Regexp.new('(\d*),?(\d*)((\[\^?[^\]]+\])+)')

matches.each do |match|
m = re.match(match)

puts "\nMatching: #{match}"
puts "--------------------"

puts "Match 1: #{m[1]}"
puts "Match 2: #{m[2]}"
puts "Match 3: #{m[3]}"
end

和输出:

Matching: 5,50[foo,bar]
--------------------
Match 1: 5
Match 2: 50
Match 3: [foo,bar]

Matching: 5,[foo][^apples]
--------------------
Match 1: 5
Match 2:
Match 3: [foo][^apples]

Matching: 10,100[baseball][^basketball][^golf]
--------------------
Match 1: 10
Match 2: 100
Match 3: [baseball][^basketball][^golf]

Matching: ,55[coke][pepsi][^drpepper][somethingElse]
--------------------
Match 1:
Match 2: 55
Match 3: [coke][pepsi][^drpepper][somethingElse]

编辑2

如果您想要标记化,按照 J-_-L 对 scan 方法的建议,添加:

m[3].scan(/\[\^?[^\]]+\]/)

关于Ruby 正则表达式帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066230/

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