0

I am quite new to regular expression and I want that in my regular expression it should accept only \\ (double back slash ) and not \ (single back slash).

         isFilePathValid: function (get) {
           var forbiddenCharactersRegexp = /[<>|?*]/,
               directorySeparatorsRegexp = /[/\\]/,
              directorySeparatorsRegexp1 = /[\\{2}]/,
              filePath = get('filePath').trim();

        return directorySeparatorsRegexp.test(filePath)
            && 
       !directorySeparatorsRegexp.test(filePath.charAt(filePath.length - 1))
            && !forbiddenCharactersRegexp.test(filePath) && 
        directorySeparatorsRegexp1.test(filePath) ;
    }

the correct file paths are 1. \\abc 2. C:\abd 3. C:\abd\abc

abc31
  • 11
  • 1
  • 3
  • Could you be more specific on this? Should the regex accept *only* two backslashes? Should it accept the backslashes amongst other characters or just on their own? Should it accept more than just 1 pair of backslashes or just the one? Provide example test cases, highlighting what would pass and what wouldn't. – George Jun 22 '17 at 09:41

2 Answers2

2

You need to make sure you have two occurences using {2}, this is the Regex you need:

/\\{2}/g

This is a Regex demo.

Edit:

Make sure you escape the \ as \\ in your string because the string parser in your program will remove one of them when "de-escaping" it for the string, you can check the discussion her and that's why it didn't work in your case.

This is a Demo snippet:

const regex = /\\{2}/g;
const str = `A sample text \\\\ that has nothing\\ on it.`;
let m;

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }

  // The result can be accessed through the `m`-variable.
  m.forEach((match, groupIndex) => {
    console.log(`Found match, group ${groupIndex}: ${match}`);
  });
}

Note the escaped \\\\ in the Demo string.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • this is my code isFilePathValid: function (get) { var forbiddenCharactersRegexp = /[<>|?*]/, directorySeparatorsRegexp = /[/\\]/, filePath = get('filePath').trim(); return directorySeparatorsRegexp.test(filePath) && !directorySeparatorsRegexp.test(filePath.charAt(filePath.length - 1)) && !forbiddenCharactersRegexp.test(filePath); } – abc31 Jun 22 '17 at 09:48
0

Try with following regular exprsssion

^^(\\\\){1}$
Mr.Pandya
  • 1,899
  • 1
  • 13
  • 24