-2

If I have a string a = I,II,III,IV,V,VI,VII,VIII

How can I use pattern to check if my input string matches any of these roman numbers?

Or is there any easier way to do so?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Iann Wu
  • 155
  • 2
  • 12
  • Take a look http://stackoverflow.com/questions/12967896/converting-integers-to-roman-numerals-java – newuser Sep 24 '13 at 05:47
  • Is this question any different than looking up `"ab"`, in `["a", "ab", "aba"]`? Please clarify. – leesei Sep 24 '13 at 05:52
  • 1
    If you literally need to match against only 7 possible strings, you don't really need regular expressions. Just brute force it. For example, you could try something like `Arrays.asList("I", "II", "III", "IV", "V", "VI", "VII").contains(a)`. – Hollis Waite Sep 24 '13 at 05:52
  • Your question is pretty unclear. About matching roman numbers see e.g. [here](http://stackoverflow.com/questions/7104623/matching-roman-numbers) and [here](http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression) – stema Sep 24 '13 at 06:05
  • Leesei, basically my goal is to use pattern to check if an input string, let's say a, is equal to any of the roman numbers. – Iann Wu Sep 24 '13 at 08:11

1 Answers1

3
    String pattern="^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";

    String input="VIII";
    if(input.matches(pattern)){
        System.out.println("true");
    }else{
        System.out.println("false");
    }

How do you match only valid roman numerals with a regular expression?

Community
  • 1
  • 1
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • 2
    This is the same regex than [in this answer](http://stackoverflow.com/a/267405/626273). There you can also find an explanation. It would be nice if you give credits to that answerer, if you reuse his solution. Btw. in Java you can omit the anchors `^` and `$`, `matches()` is always matching against the whole input. – stema Sep 24 '13 at 06:10
  • thanks alot Prabhakaran! Btw how do you come up with the pattern string? – Iann Wu Sep 24 '13 at 08:12