问题描述
我用 Regex.fromLiteral(".*")
创建了一个非常简单的匹配所有正则表达式.
I've created a very simple match-all Regex with Regex.fromLiteral(".*")
.
根据文档:返回指定文字字符串的文字正则表达式."
According to the documentation: "Returns a literal regex for the specified literal string."
但我真的不明白对于指定的文字字符串"应该是什么意思.
But I don't really get what "for the specified literal string" is supposed to mean.
考虑这个例子:
fun main(args: Array<String>) {
val regex1 = ".*".toRegex()
val regex2 = Regex.fromLiteral(".*")
println("regex1 matches abc: " + regex1.matches("abc"))
println("regex2 matches abc: " + regex2.matches("abc"))
println("regex2 matches .* : " + regex2.matches(".*"))
}
输出:
regex1 matches abc: true
regex2 matches abc: false
regex2 matches .* : true
很明显(和我的预期相反),Regex.fromLiteral()
和 String.toRegex()
表现完全不同(我尝试了几十种不同的参数到 regex2.matches()
- 唯一返回 true 的是 .*
)
so apparently (and contrary to my expectations), Regex.fromLiteral()
and String.toRegex()
behave completely different (I've tried dozens of different arguments to regex2.matches()
- the only one that returned true was .*
)
这是否意味着用 Regex.fromLiteral()
创建的正则表达式总是只匹配它创建的确切字符串?
Does this mean that a Regex created with Regex.fromLiteral()
always matches only the exact string it was created with?
如果是,那么这种正则表达式有哪些可能的用例?(我想不出任何有用的场景)
If yes, what are possible use cases for such a Regex? (I can't think of any scenario where that would be useful)
推荐答案
是的,它确实创建了一个与 String
中的文字字符匹配的正则表达式.当您尝试匹配将在正则表达式中解释的符号时,这很方便 - 您不必以这种方式转义它们.
Yes, it does indeed create a regex that matches the literal characters in the String
. This is handy when you're trying to match symbols that would be interpreted in a regex - you don't have to escape them this way.
例如,如果您要查找包含 .*[](1)?[2]
的字符串,您可以执行以下操作:
For example, if you're looking for strings that contain .*[](1)?[2]
, you could do the following:
val regex = Regex.fromLiteral(".*[](1)?[2]")
regex.containsMatchIn("foo") // false
regex.containsMatchIn("abc.*[](1)?[2]abc") // true
当然,您几乎可以使用 Regex
执行任何您可以使用的常规 String
方法.
Of course you can do almost anything you can do with a Regex
with just regular String
methods too.
val literal = ".*[](1)?[2]"
literal == "foo" // equality checks
literal in "abc.*[](1)?[2]abc" // containment checks
"some string".replace(literal, "new") // replacements
但有时您需要一个 Regex
实例作为参数,因此在这些情况下可以使用 fromLiteral
方法.对于某些用例,这些针对不同输入的不同操作的性能也可能很有趣.
But sometimes you need a Regex
instance as a parameter, so the fromLiteral
method can be used in those cases. Performance of these different operations for different inputs could also be interesting for some use cases.
这篇关于使用 Regex.fromLiteral() 创建的 Regex 到底匹配什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!