The landlord of the two days to deal with a demand to match the Roman numerals in the string in a number of strings and take these Roman numbers for a series of operations. In the degree Niang on the search for a long day also did not find useful information also by a lot of wrong code misled the very painful. Fortunately, the last kinds of efforts It took half a day to reach the desired result. Now record and share it here. If you need to reprint please specify the source to write the portal. Thanks
Here to share a website can convert Arabic numerals to the corresponding Roman numerals no limit easy to use and share
Http://www.zhongguosou.com/education_graduate_course_tools/roman_numeral_convert.aspx
The following methods will take the Roman numerals in the string, but will also match the above string, so you need to post-process
/** * has been tested successfully take out regular expression matching string * @author Erikas * @throws Exception */@org. junit.testpublic void Testreg () throws Ex ception {String str = "";//matches the regular of Roman numerals, but since each of them may be 0 empty strings will also be matched to be later in the program to process string regex = "(-| +|^) m{0,9} (cm| cd| D? c{0,3}) (xc| xl| L? x{0,3}) (ix|iv| V? i{0,3}) (+|$) "; Pattern p = pattern.compile (regex); Matcher Matcher = P.matcher (str); list<string> list = new arraylist<string> (); while (Matcher.find ()) {//matcher.find () returns true to match the result But after execution, if there is no subsequent match, the success will immediately become falseSystem.out.println ("here"); String srcstr = Matcher.group ();//Put the result of the removal into Listlist.add (SRCSTR);} SYSTEM.OUT.PRINTLN (list);}
The following methods are used to convert Roman numerals to corresponding Arabic numerals.
Roman numerals to Arabic numerals://Back to the Roman numerals, if a number is smaller than the previous number, add that number to the result; //vice versa, subtract the previous number two times in the result and add the current number; //I, V, X, L, C, D, M //1. 5, 10, 50, 100, 500, $ private static int r2a (String in) { int graph[] = new int[400]; graph[' I '] = 1; graph[' V ']=5; graph[' X ']=10; graph[' L ']=50; graph[' C ']=100; graph[' D ']=500; graph[' M ']=1000; char[] num = In.tochararray (); Traverse this number, with Sum to total and int sum = graph[num[0]]; for (int i=0; i<num.length-1; i++) { //If, I is larger than i+1, add directly if (Graph[num[i]] >= graph[num[i+1]]) { Sum + = graph[num[i+1]]; } If I is smaller than i+1, sum sum minus I this place number twice times, plus i+1//is equivalent to the number of the left side of the number is larger than the number of the left, then the numbers on the right minus else{ sum = sum + graph[num[i+ 1]]-2*graph[num[i]]; } } return sum; }
The regular expression matches the Roman number and returns the match to the value