Regex for roman numeral to integer

Viewed 54

This regex is meant for matching ocurrences listed in next table. Then I will turn every match into it's corresponding integer value

const regex = /[I,V,X,L,C,D,M,IV,IX,XL,XC,CD,CM]/g
Roman numeral Integer value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
IV 4
IX 9
XL 40
XC 90
CD 400
CM 900

For this particular string example I want the code snippet to match only ['XC'] however it's actually returning ['X','C'] separately.

const regex = /[I,V,X,L,C,D,M,IV,IX,XL,XC,CD,CM]/g
const test = 'XC'
console.log(test.match(regex))

Is it possible to achive this by using regex?

1 Answers

You have RegExp:

const regex = /[I,V,X,L,C,D,M,IV,IX,XL,XC,CD,CM]/g

and string XC, in which you do matching. RegExp is going through your string and matches each symbol in [...], because grouping in RegExp is done by (..|..|..), so first it finds X in XC, then C.

You can change your program logic a bit and create roman-arabic number object from your table. After this you'll have easy access to roman-arabic dictionary. Check inline comments:

// Create roman number object
const romNumObj = {
  I: 1, V: 5, X: 10, L: 50, C: 100,
  D: 500, M: 1000, IV: 4, IX: 9,
  XL: 40, XC: 90, CD: 400, CM: 900
};

// Find romNum function
const romNum = code => romNumObj[code] ? romNumObj[code] : false;

// Test
console.log(`XC: ${romNum('XC')}`);
console.log(`I+I: ${romNum('I') + romNum('I')}`);
console.log(`DC: ${romNum('DC')}`);

Related