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

后端 未结 2 788
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题