我现在不能使用令人难以置信的tr(),因为我只能使用Groovy1.7.1,我想知道是否有一种优雅的方法在用Base32编码的字符串和数字之间来回移动,但是值是A到Z然后是2到7,而不是0到9然后是A到V。
这是为了通过不使用0或1来消除键入人类可读代码时的客户错误。
我可以想到72个Regex表达式来实现这一点,但在以下情况下,这似乎有点过分了
tr( 'A-Z2-7', 0-9A-V')要简单得多
发布于 2010-07-25 08:32:29
Groovy的美妙之处在于它的动态性。如果你需要这个特性,但它不在那里,那就添加它!在您的应用程序的某个方便的入口点中,或者在需要它的类中的静态块中,添加直接从1.7.3+源代码中提升的代码:
String.metaClass.'static'.tr = { String text, String source, String replacement ->
if (!text || !source) { return text }
source = expandHyphen(source)
replacement = expandHyphen(replacement)
// padding replacement with a last character, if necessary
replacement = replacement.padRight(source.size(), replacement[replacement.size() - 1])
return text.collect { original ->
if (source.contains(original)) {
replacement[source.lastIndexOf(original)]
} else {
original
}
}.join()
}
String.metaClass.'static'.expandHyphen = { String text ->
if (!text.contains('-')) { return text }
return text.replaceAll(/(.)-(.)/, { all, begin, end -> (begin..end).join() })
}
String.metaClass.tr = { String source, String replacement ->
String.tr(delegate, source, replacement)
}这样做的好处是,只要你能升级到1.7.3,你就可以移除这个元魔法,而不需要改变你的其他源码。
https://stackoverflow.com/questions/3325564
复制相似问题