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

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

    Im answering this question Regular Expression in Python for Roman Numerals here
    because it was marked as an exact duplicate of this question.

    It might be similar in name, but this is a specific regex question / problem
    as can be seen by this answer to that question.

    The items being sought can be combined into a single alternation and then
    encased inside a capture group that will be put into a list with the findall()
    function.
    It is done like this :

    >>> import re
    >>> target = (
    ... r"this should pass v" + "\n"
    ... r"this is a test iii" + "\n"
    ... )
    >>>
    >>> re.findall( r"(?m)\s(i{1,3}v*|v)$", target )
    ['v', 'iii']
    

    The regex modifications to factor and capture just the numerals are this :

     (?m)
     \s 
     (                     # (1 start)
          i{1,3} 
          v* 
       |  v
     )                     # (1 end)
     $
    

提交回复
热议问题