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

前端 未结 16 2396
無奈伤痛
無奈伤痛 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条回答
  •  萌比男神i
    2020-11-22 03:18

    import re
    pattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$'
    if re.search(pattern, 'XCCMCI'):
        print 'Valid Roman'
    else:
        print 'Not valid Roman'
    

    For people who really want to understand the logic, please take a look at a step by step explanation on 3 pages on diveintopython.

    The only difference from original solution (which had M{0,4}) is because I found that 'MMMM' is not a valid Roman numeral (also old Romans most probably have not thought about that huge number and will disagree with me). If you are one of disagreing old Romans, please forgive me and use {0,4} version.

提交回复
热议问题