What exactly does a Regex created with Regex.fromLiteral() match?

后端 未结 2 783
遇见更好的自我
遇见更好的自我 2020-12-11 18:42

I\'ve created a very simple match-all Regex with Regex.fromLiteral(\".*\").

According to the documentation: \"Returns a literal regex for the specified

相关标签:
2条回答
  • 2020-12-11 19:28

    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))

    0 讨论(0)
  • 2020-12-11 19:35

    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.

    0 讨论(0)
提交回复
热议问题