Escape string to be passed as regex

Viewed 11909

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?

2 Answers
Related