{Kotlin学习日记}Day22 Koan第六关

大家好,我是William。今天是Koan第六关,String,字符串处理。

开始闯关:

https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Strings/Task.kt

Introduction

Strings

Read about different string literals and string templates in Kotlin.
Raw strings are useful for writing regex patterns, you don't need to escape a backslash by a backslash. Below there is a pattern that matches a date in format 13.06.1992 (two digits, a dot, two digits, a dot, four digits):

fun getPattern() = """\d{2}\.\d{2}\.\d{4}"""

Using month variable rewrite this pattern in such a way that it matches the date in format 13 JUN 1992 (two digits, a whitespace, a month abbreviation, a whitespace, four digits).

解:
本题比较简单,主要是先叫你看看那个different string literals and string templates,然后了解一下string在kotlin里面的处理方式,例如 """ 三引号处理(又抄袭了Python,不过抄的很好,我喜欢),还有$美元占位符处理(抄袭了C\C++的%s占位符)。最后是要求你按照上面getPattern()函数那样,写一个字符串来显示正则表达式。

答:
对正则表达式有什么不懂的话,可以直接到这个网站http://regexr.com/学习,我个人力推哦,比直接看《正则表达式某某指南》学得更快,因为可以尝试嘛。

val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"
// 就这么简单
fun getPattern(): String = """\d{2}\s$month\s\d{4}"""

小结

我想写的更短一些,减少大家阅读数,同时也是减少我的复习时间(我也是人啊,我也很健忘的)。对于Koan系列这种短篇日记会尽量控制在400字以内。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容