我能想到最简单的解决方法,而且付出最少的努力就是在已经有的组和
+
周围添加一个额外的捕获组。即:
/(\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(/\[\^?[^\]]+\]/)
[foo][^apples]
,并且最后一个术语单独返回 -[^apples]
,我猜测它能够找到匹配项,但是输出结果中没有出现。不知道我错过了什么。 - Anurag][
进行拆分--据我所知,没有一种语言允许在其正则表达式引擎中具有可变数量的捕获组。我在Ruby中编写了一个快速且不完美的检查,我将其作为编辑发布。告诉我是否误读了你的问题。 - photoionized