How do you match only valid roman numerals with a regular expression?

前端 未结 16 2501
無奈伤痛
無奈伤痛 2020-11-22 02:44

Thinking about my other problem, i decided I can\'t even create a regular expression that will match roman numerals (let alone a context-free grammar that will generate them

16条回答
  •  感动是毒
    2020-11-22 03:21

    Just to save it here:

    (^(?=[MDCLXVI])M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$)
    

    Matches all the Roman numerals. Doesn't care about empty strings (requires at least one Roman numeral letter). Should work in PCRE, Perl, Python and Ruby.

    Online Ruby demo: http://rubular.com/r/KLPR1zq3Hj

    Online Conversion: http://www.onlineconversion.com/roman_numerals_advanced.htm

提交回复
热议问题