Escape string to be passed as regex

前端 未结 2 987
野的像风
野的像风 2020-12-10 10:50

I would like to create a function that creates regex matching an arbitrary string given at the input. For example, when I feed it with 123$ it should match lite

相关标签:
2条回答
  • 2020-12-10 11:07

    You can use Java's Pattern class to escape strings as regular expressions. See http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29

    For example:

    scala> Pattern.quote("123$").r.findFirstIn("123$")
    res3: Option[String] = Some(123$)
    
    0 讨论(0)
  • 2020-12-10 11:11

    Just to bring more attention to Harold L's comment above, if you want to do this with a Scala library you can use:

    import scala.util.matching.Regex
    Regex.quote("123$").r.findFirstIn("123$")
    
    0 讨论(0)
提交回复
热议问题