DEV Community

ouryperd
ouryperd

Posted on

Write a method like Python's string.printable in Groovy

To find out if a string has only printable characters, Python has a function called string.printable. We can make our own String.isPrintable() using metaprogramming in Groovy.

import java.nio.charset.Charset

String.metaClass.isPrintable = { return Charset.forName("US-ASCII")
                                           .newEncoder()
                                           .canEncode(delegate) 
                           }

assert 'Abc'.isPrintable() == true
assert 'àé'.isPrintable() == false
assert 'môre'.isPrintable() == false
assert 'de076'.isPrintable() == true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)