0

I know there are many questions about variables in regex. Some of them for instance:

Unfortunately none of them explains in detail how to escape my RegExp.

Let's say I want to find all files that have this string before them:

file:///storage/sdcard0/

I tried this with regex:

(?:file:\/\/\/storage\/sdcard0\(.*))(?:\"|\')

which correctly got my image1.jpg and image2.jpg in certain json file. (tried with http://regex101.com/#javascript)

For the life of me I can't get this to work inside JS. I know you should use RegExp to solve this, but I'm having issues.

var findStr =  "file:///storage/sdcard0/";
var regex =  "(?:"+ findStr +"(.*))(?:\"|\')";
var re = new RegExp(regex,"g"); 
var result = <mySearchStringVariable>.match(re);

With this I get 1 result and it's wrong (bunch of text). I reckon I should escape this as said all over the web.. I tried to escape findStr with both functions below and the result was the same. So I thought OK I need to escape some chars inside regex also.

I tried to manually escape them and the result was no matches.

I tried to escape the whole regex variable before passing it to RegExp constructor and the result was the same: no matches.

function quote(regex) {
  return regex.replace(/([()[{*+.$^\\|?])/g, '\\$1');
}   

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}   

What the hell am I doing wrong, please?

Is there any good documentation on how to write RegExp with variables in it?

Community
  • 1
  • 1
trainoasis
  • 6,419
  • 12
  • 51
  • 82
  • Why are you including the quote characters at the end of your pattern? That doesn't make sense to me. – Pointy Jul 22 '14 at 13:59
  • Quote is the ending character of my match, the point where I want to stop matching.. – trainoasis Jul 22 '14 at 14:01
  • Actually your regex works perfectly well for me. You're going to have to post more detail. – Pointy Jul 22 '14 at 14:01
  • 1
    When I do `"foo bar file:///storage/sdcard0/'".match(re)` I get the correct result, in other words - just the file URL and not the "foo bar". – Pointy Jul 22 '14 at 14:04
  • possible duplicate of [How to escape regular expression in javascript?](http://stackoverflow.com/questions/2593637/how-to-escape-regular-expression-in-javascript) – Tom Fenech Jul 22 '14 at 14:09
  • @Pointy string to search from is received with var string = JSON.stringify(json); - could this be a problem? – trainoasis Jul 22 '14 at 14:18
  • 1
    Ahhhh - i figured it out!! I needed to use LAZY with (.*?) damn never thought of that before – trainoasis Jul 22 '14 at 14:24

1 Answers1

0

All I needed to do was use LAZY instead of greedy with

var regex =  "(?:"+ findStr +"(.*?))(?:\"|\')"; // added ? in (.*?)
trainoasis
  • 6,419
  • 12
  • 51
  • 82