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?

7
  • Why are you including the quote characters at the end of your pattern? That doesn't make sense to me. Commented Jul 22, 2014 at 13:59
  • Quote is the ending character of my match, the point where I want to stop matching.. Commented Jul 22, 2014 at 14:01
  • Actually your regex works perfectly well for me. You're going to have to post more detail. Commented Jul 22, 2014 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". Commented Jul 22, 2014 at 14:04
  • 1
    Ahhhh - i figured it out!! I needed to use LAZY with (.*?) damn never thought of that before Commented Jul 22, 2014 at 14:24

1 Answer 1

0

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

var regex =  "(?:"+ findStr +"(.*?))(?:\"|\')"; // added ? in (.*?)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.