Match roman numerals using regex

Original link: https://www.williamlong.info/archives/6984.html

Programming.jpg

Roman numerals are a type of numerals used in Europe before the introduction of Arabic numerals, and are less used now. It came into being later than the numbers in Chinese oracle bone inscriptions, and even later than the decimal numbers of the Egyptians.

Roman numerals are a type of numerals used before the introduction of Arabic numerals. It uses seven Roman letters as numbers, namely I (1), X (10), C (100), M (1000), V (5), L (50), D (500). The numbering method of Roman numerals is: the same numbers are consecutively written, and the number represented is equal to the number obtained by adding these numbers; the smaller number is on the right of the larger number, and the number represented is equal to the number obtained by adding these numbers; The number is to the left of the large number, and the number represented is equal to the number obtained by subtracting the large number.

When programming, sometimes there is a problem of using regular expressions to match Roman numerals. Here is a solution:

Unvalidated Roman numerals:

^[MDCLXVI]+$

Strict validation of Roman numerals:

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

Flexible validation of Roman numerals:

^(?=[MDCLXVI])M*(C[MD]|D?C*)(X[CL]|L?X*)(I[XV]|V?I*)$

Simple Roman Numerals:

^(?=[MDCLXVI])M*D?C{0,4}L?X{0,4}V?I{0,4}$

Programming languages ​​for the above regular expressions: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

This article is reprinted from: https://www.williamlong.info/archives/6984.html
This site is for inclusion only, and the copyright belongs to the original author.