[Solved] How do you match valid integers and roman numerals with a regular expression?


Assuming that you just want decimal integers in regular form (e.g., 1000 would be valid, 1e3 [the same number in scientific notation] would not), the regular expression to validate that is \d+, which means “one or more digit(s).”

To have your regular expression allow that, you’d want an alternation, which lets either of two alternatives match. Alternations are in the form first|second where first and second are the alternatives.

Since your current expression has “beginning” and “end” of input assertions (^ and $), we’d either want to include those in the second alternative as well, or put the entire alternation in a non-capturing group.

So either:

    /^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$|^\d+$/
// Note -----------------------------------------------------^^^^^^

(on regex101)

or

    /^(?:M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|\d+)$/
//    ^^^                                                      ^^^^^

(on regex101)

Note that your original expression has a few capture groups (but doesn’t entirely consist of captures); if you wanted to capture the \d+ part, you’d put () around it.

3

solved How do you match valid integers and roman numerals with a regular expression?