【问题标题】:Groovy Base32 conversionsGroovy Base32 转换
【发布时间】:2011-03-20 12:39:44
【问题描述】:

目前我无法使用美妙的 tr(),因为我只能使用 Groovy 1.7.1,并且想知道是否有一种优雅的方式可以在使用 Base32 编码的字符串和数字之间来回移动,但是使用值 A 到 Z 然后 2 到 7,而不是 0 到 9 然后 A 到 V。

这是为了消除客户在键入人类可读代码时的错误,不使用零或一。

我能想到 72 种正则表达式可以实现这一点,但是当

tr( 'A-Z2-7', 0-9A-V')

简单多了

【问题讨论】:

    标签: string xcode groovy translate base32


    【解决方案1】:

    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,您就可以删除此元魔法,而无需更改其他来源。

    【讨论】:

    • Delphyne,这证明了为什么更多的头比一个更好。我对 Groovy 还是很陌生,我在 Filemaker 中使用它,所以我只是在一个单一的途径上看这个,当然这只是一种享受。我需要对文档和源代码更加熟悉。非常感谢您的意见。
    • 我必须去哪里查看源代码以便开始扩展我的学习??
    • 源代码可与二进制文件 [1] 一起下载。诀窍在于,弄清楚事情在哪里实现可能并不明显。在我上面发布的代码中,静态 'tr' 和 'expandHyphen' 方法存在于一个名为 StringUtils 的类中,而实例 'tr' 方法存在于 DefaultGroovyMethods 中。 [1]groovy.codehaus.org/Download
    猜你喜欢
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 2010-11-19
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    相关资源
    最近更新 更多