-1

I'm writing a program to convert Roman numerals into integers. The method I'm doing is looking for a sub-string which would signify subtractions (IX, CM, XC) and adding the respective amount to the tally. For example if CM is in the string MMMMCMXCIX then set the hundreds column to 9.

I'm trying to do it with

    if(romanNum.matches("CM")){
        hundreds = 9;
        romanNum.replaceAll("CM", "");
    }

but it never enters the if statement. Using these two regular expression checkers with the string MMMMCMXCIX and the regular expression solely as CM they both highlight a match yet my code suggests otherwise. Why is this?

Nanor
  • 2,400
  • 6
  • 35
  • 66
  • `Matcher.matches()` checks if **all of the input** matches the pattern, in other words, it only matches in if the input is exactly `CM` and not if it is `MMMMCMXCIX`. Use other methods instead, such as [`Matcher.find()`](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#find--). – Jesper Aug 19 '16 at 14:05
  • There are several issues with the code. 1) Use `contains` to check if a string contains a substring, 2) assign replaced values to a variable, 3) replacing literal substrings should be done with `String#replace`, not `replaceAll`. – Wiktor Stribiżew Aug 19 '16 at 14:06

1 Answers1

0

String#matches matches the whole String against your substring, which is why your condition never triggers unless your String value only consists in "CM".

Either:

  1. use String#contains (no regular expressions):

    e.g. if(romanNum.contains("CM"))

  2. or, use a Matcher against a Pattern explicitly:

    e.g. if (Pattern.compile("CM").matcher(romanNum).find())

    Note that this doesn't make sense as is (prefer solution 1), unless you have an actual pattern.

Finally, you probably want to use replace instead of replaceAll if you're only replacing literals.

Mena
  • 47,782
  • 11
  • 87
  • 106