“I like your Roman Numeral library. I needed a function to test for Roman numerals, so I wrote this one.
// Check to see if the string is a Roman Numeral
// NOTE: this doesn't check for fractions, overbars, the Bede "N" (zero) etc.
// NOTE: It also doesn't check for a well-formed Roman Numeral.
function is_roman_numeral( $roman )
{
// Strip every non-word character
// - A-Z, 0-9, apostrophe and understcore are what's left
$roman = preg_replace( "/[^A-Z0-9_']/iu", "", $roman );
// if it contains anything other than MDCLXVI, then it's not a Roman Numeral
$result = preg_match( "/[^MDCLXVI]/u", $roman );
if( $result )
{
return FALSE;
}
return TRUE;
}
Who knows if blogger is going to show it properly. If not, just contact me and I'll send it you in email or something. Anyway, it's something I wrote in 5 minutes. If you want to add it to your library, modified or otherwise, please feel free.”
Thanks for writing in Keith, and sorry for the late response. There are two ways to validate a Roman number, using regular expressions like you did, and converting back to an Arabic number (if the conversion fails, it's not a Roman number).
I'm not sure about using a regular expression to remove non-word characters. My gut tells me that anything containing such characters should fail validation as a Roman number. Also, I would reverse the match and eliminate the
if
statement by directly returning the result of the match.PHP
function isRoman($roman)
{
return preg_match("/[MDCLXVI]/u", $roman);
}
ASP
function isRoman(roman)
dim regEx
set regEx = new RegExp
with regEx
.IgnoreCase = true
.Global = true
.Pattern = "[MDCLXVI]"
end with
if regEx.Test(roman) then
isRoman = true
else
isRoman = false
end if
set regEx = nothing
end function
No comments:
Post a Comment