我对正则表达式很陌生,我希望在我的正则表达式中它只接受\\
(双反斜杠)而不是\
(单反斜杠)。
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) ;
}
正确的文件路径是 1. \\ abc 2. C:\ abd 3. C:\ abd \ abc
答案 0 :(得分:1)
您需要确保使用{2}
发生两次,这是您需要的正则表达式:
/\\{2}/g
这是Regex demo。
修改强>
确保将\
转义为字符串中的\\
,因为程序中的字符串解析器会在为字符串“解除转义”时删除其中一个,您可以检查{{ 3}}这就是为什么它在你的情况下不起作用。
这是一个演示片段:
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}`);
});
}
请注意演示字符串中的转义\\\\
。
答案 1 :(得分:0)
尝试遵循常规exprsssion
^^(\\\\){1}$