IsBase64
From EggeWiki
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.
static boolean isBase64(String s) { return (s.length() % 4 == 0) && s.matches("^[A-Za-z0-9+/]+[=]{0,2}$"); }
@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!")); }
Python
The same function in Python:
def isBase64(s): return (len(s) % 4 == 0) and re.match('^[A-Za-z0-9+/]+[=]{0,2}$', s)
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.
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$


