Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

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

There is a very helpful article on how to validate roman numerals How do you match only valid roman numerals with a regular expression?

Regex has always been my achilles heel in spite of all my efforts. How do I expand the regular expression provided to match normal integers as well? The provided regular expression is:

/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...