Joel VanderWerf
6/5/2009 10:39:00 PM
Robert Schaaf wrote:
> Now I know this is only peripherally topical, but can anyone come up
> with the regexp that achieves this:
>
> string =~ pattern
> [$1, $2, $3]
>
> where string is a Roman numeral, optionall followed by "(?)" or alpha,
> which, if present can be followed by an Arabic number,
>
> produces
>
> I -> ["I", nil, nil]
> I(?) -> ["I", "(?)", nil]
> Ia -> ["I", "a", nil]
> Ib -> ["I", "b", nil]
> IIa1 -> ["II", "a", "1"]
> IIa2 -> ["II", "a", "2"]
Do you need the regex to validate the Roman numeral itself? If not, the
following passes your tests (assuming that you don't mind compacting out
the nils). You can do validation subsequently.
rx = /\A([IVXLCDM]+)(?:(\(\?\))|([a-z])(\d+)?)?\z/
strs = [
["I", ["I", nil, nil]],
["I(?)", ["I", "(?)", nil]],
["Ia", ["I", "a", nil]],
["Ib", ["I", "b", nil]],
["IIa1", ["II", "a", "1"]],
["IIa2", ["II", "a", "2"]]
]
strs.each do |str, expected|
if rx.match str
match = $~.captures
if match.compact == expected.compact
puts "#{str.inspect} ok"
else
puts "#{str.inspect} fails: match=#{match.inspect}"
end
else
puts "#{str.inspect} fails: not matched"
end
end
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407