IsBase64: Difference between revisions
mNo edit summary |
mNo edit summary |
||
Line 23: | Line 23: | ||
def isBase64(s): | def isBase64(s): | ||
return (len(s) % 4 == 0) and re.match('^[A-Za-z0-9+/]+[=]{0,2}$', s) | return (len(s) % 4 == 0) and re.match('^[A-Za-z0-9+/]+[=]{0,2}$', s) | ||
</geshi> | |||
=== Regex === | |||
In both of the above examples, I check the length, and then apply the regex. I think this makes it a bit more readable. However, it is possible to do the entire check with just a single regex. | |||
<geshi> | |||
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ | |||
</geshi> | </geshi> | ||
[[Category:Java]] | [[Category:Java]] | ||
[[Category:Regex]] | [[Category:Regex]] |
Latest revision as of 03:02, 19 October 2009
Test to determine if a string is base64 encoded. This check only shows if the string conforms to base64. It's possible that the string conforms, but is not in fact encoded.
<geshi lang="java5"> static boolean isBase64(String s) { return (s.length() % 4 == 0) && s.matches("^[A-Za-z0-9+/]+[=]{0,2}$"); } </geshi>
<geshi lang="java5"> @Test public void testIsBase64() throws Exception { Assert.assertTrue(RssFileUpload.isBase64("bGVhc3VyZS4=")); Assert.assertTrue(RssFileUpload.isBase64("ZWFzdXJlLg==")); Assert.assertTrue(RssFileUpload.isBase64("YXN1cmUu")); Assert.assertTrue(RssFileUpload.isBase64("c3VyZS4=")); Assert.assertFalse(RssFileUpload.isBase64("OMG!")); } </geshi>
Python
The same function in Python: <geshi lang="python"> def isBase64(s):
return (len(s) % 4 == 0) and re.match('^[A-Za-z0-9+/]+[=]{0,2}$', s)
</geshi>
Regex
In both of the above examples, I check the length, and then apply the regex. I think this makes it a bit more readable. However, it is possible to do the entire check with just a single regex.
<geshi> ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ </geshi>