如何使用Regex

时间:2018-05-23 18:58:11

标签: regex kotlin

我在Kotlin中定义的列表如下 -

val spices = listOf("curry", "pepper", "cayenne", "ginger", "red curry", "green curry", "red pepper" )

现在我要过滤以c开头并以e结尾的香料。如果我尝试下面的代码,我会得到满意的结果 [cayenne] -

val filteredSpices = spices.filter { it.first() == 'c' && it.last() == 'e'}

但是当我尝试使用代码时,它会返回一个空列表---

val filteredSpices = spices.filter { it.matches(Regex.fromLiteral("^[c].*[e]$")) }

我在编写解决方案之前测试了正则表达式。正则表达式工作正常但无法过滤列表中的任何元素

为什么失败?我做错了什么?我已经在 Intelli J Idea REPL 上尝试了代码。

人们建议我使用 Regex() 代替 Regex.fromLiteral() ,这有效。但是,如果我们在下面看看它们的实施情况---

Regex() - public constructor(pattern: String): this(Pattern.compile(pattern))

Regex.fromLiteral() --- public fun fromLiteral(literal: String): Regex = literal.toRegex(RegexOption.LITERAL)

literal.toRegex()的实现就像以下---

public inline fun String.toRegex(option: RegexOption): Regex = Regex(this, option)

他们实际上都返回 Regex 。它们之间的唯一区别是 - Regex.fromLiteral() 会使用名为 RegexOption.LITERAL 的选项返回正则表达式

我想了解它们为何以及如何完全不同?

0 个答案:

没有答案