Regex to identify roman numerals followed by " - " at the start of a line

98 Views Asked by At

I am trying to create a regex expression that matches roman numerals (from 1 to 99) followed by " - " or by " – ". It should only match if the roman numeral is at the start of a line. I want to add a newline before each match. The example string is:

VI - lealdade e ética;  
VII - busca da verdade real;  
VIII - livre convencimento técnico-jurídico do delegado de polícia;  
IX - controle de legalidade dos atos policiais civis;  
X - uso diferenciado da força para preservação da vida, redução do sofrimento e o inciso  
II redução de danos;  
XI – continuidade investigativa  
criminal;  
XII – atuação imparcial na condução da atividade  
investigativa e de polícia judiciária;  
XIII – política de gestão direcionada à proteção e  
à valorização dos seus  
integrantes;  
XIV – unidade de doutrina e uniformidade de  
procedimento;  
XV – autonomia, imparcialidade, tecnicidade e cientificidade investigativa, indiciatória, inquisitória, notarial e pericial; "

Using the pattern r'^(I{1,3}|IV|V|VI{1,3}|IX|X{1,3}|XL|L -|– )', I can insert a newline before each roman numerals followed by " - " or " – ".
The problem is that it is also inserting a newline before "II redução de danos;". How can I correct this behaviour?

Using the pattern r'^(I{1,3}|IV|V|VI{1,3}|IX|X{1,3}|XL|L) (?:-|–) ', I can insert a newline only before roman numerals followed by " - ". Why?

1

There are 1 best solutions below

0
On

With 99 values, there's both a great many and complex combinations for a regex, while not so many a simple list isn't easy to create and manage - consider either just testing if the line .startswith(tuple_of_values) the values or building your regex programmatically from it

mapping = {
    "I": 1,
    "II": 2,
    ...
    "XCIX": 100,
}

numerals_regex = re.compile("^(" + str("|".join(mapping.keys())) + ") (-|–) (.*)$")

for line in lines:
    match = numerals_regex.match(line.rstrip())
    if match is None:
        # opportunity to deal with line in some other way
        continue
    # line matched!