Link to home
Start Free TrialLog in
Avatar of Edgard Yamashita
Edgard YamashitaFlag for Brazil

asked on

c# -find roman numerals and convert to int

hello everybody.. im in a bit of problem now..

i need to find roman numerals in a string and convert it to int eg:

"XIV VARA CIVIL" = int 14
"VARA CIVIL XX" = int 20

does anyone know if there is any method for it in web? maybe a regex to find could work but i have no clue or time to make such conversor

thx for the help!

Avatar of Erick37
Erick37
Flag of United States of America image

Will the numerals always be at either the beginning or end of the string?
Will "VARA CIVIL" always be in the string?
Avatar of Edgard Yamashita

ASKER

not really.. that was just a sample..

the roman numerals could be anywhere in the string (most of the time they are at either the beggining or at the end, but i cant be sure if that would be always the case)

but the text it will be different everytime.

is it possible to do such thing ?
Avatar of ajb2222
ajb2222

Since the roman numeral will always be a word, first break the string into it's component words.

         string y = "VARA CIVIL XX";
         string[] x = y.Split(' ');

this makes anarray of strings
     x[0] = "VERA"
     x[1] = "CIVIL"
     x[2] = "XX"

then try each value in the string array x to see if it is a valid roman numeral.

Here is a link to an example of how to convert a roman numeral to a number.
http://www.blackwasp.co.uk/RomanToNumber.aspx
You could do a regex match with pattern:
(?i)\b(?=[ivxlcdm]+)M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})\b

Based on, but slightly modified from, a pattern from: http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression

That would capture only valid roman numerals, I believe - then you'd have to convert them to an integer.
ASKER CERTIFIED SOLUTION
Avatar of jmcmunn
jmcmunn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial