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

1
  • 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. Commented Jun 22, 2017 at 9:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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); }
0

Try with following regular exprsssion

^^(\\\\){1}$

3 Comments

this will accept \\, \\\\, and any other multiple of 2
You need only double
try this ^(\\\\){1}$

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.