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

前端 未结 16 2382
無奈伤痛
無奈伤痛 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:23

    The following expression worked for me to validate the roman number.

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

    Here,

    • M{0,4} will match thousands
    • C[MD]|D?C{0,3} will match Hundreds
    • X[CL]|L?X{0,3} will match Tens
    • I[XV]|V?I{0,3} will match Units

    Below is a visualization that helps to understand what it is doing, preceded by two online demos:

    Debuggex Demo

    Regex 101 Demo

    Python Code:

    import re
    regex = re.compile("^M{0,4}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$")
    matchArray = regex.match("MMMCMXCIX")
    

提交回复
热议问题