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

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

    The positive look-behind and look-ahead suggested by @paxdiablo in order to avoid matching empty strings seems not working to me.

    I have fixed it by using negative look-ahead instead :

    (?!$)M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})
    

    NB: if you append something (eg. "foobar" at the end of the regex, then obviously you'll have to replace (?!$) by (?!f) (where f is the first character of "foobar").

提交回复
热议问题