Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

scala - Escape string to be passed as regex

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 :(                                               

So the last findAllIn should find d+ in text, but it doesn't. What's wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...