I\'ve created a very simple match-all Regex with Regex.fromLiteral(\".*\").
According to the documentation: \"Returns a literal regex for the specified
The Regex.fromLiteral() instantiates a regex object while escaping the special regex metacharacters. The pattern you get is actually \.\*, and since you used matches() that requires a full string match, you can only match a .* string with it (with find() you could match it anywhere inside a string).
See the source code:
public fun fromLiteral(literal: String): Regex = Regex(escape(literal))
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.
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
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
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.