问题描述
我想创建一个函数来创建与输入中给出的任意字符串匹配的正则表达式.例如,当我用 123$
提供它时,它应该在字面上匹配 "123$"
而不是 123
在字符串.
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 literally "123$"
and not 123
at the end of the string.
def convert( xs: String ) = (xs map ( x => "\\"+x)).mkString
val text = """ 123 \d+ 567 """
val x = """\d+"""
val p1 = x.r
val p2 = convert(x).r
println( p1.toString )
\d+ // regex to match number
println( ( p1 findAllIn text ).toList )
List(123, 567) // ok, numbers are matched
println( p2.toString )
\\\d\+ // regex to match "backshash d plus"
println( ( p2 findAllIn text ).toList )
List() // nothing matched :(
所以最后一个 findAllIn
应该在文本中找到 \d+
,但它没有.这里有什么问题吗?
So the last findAllIn
should find \d+
in text, but it doesn't. What's wrong here?
推荐答案
您可以使用 Java 的 Pattern 类将字符串转义为正则表达式.请参阅 http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29
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
例如:
scala> Pattern.quote("123$").r.findFirstIn("123$")
res3: Option[String] = Some(123$)
这篇关于要作为正则表达式传递的转义字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!