正则获取文件名,'E:/**/lib/viser-vue/index.js'

版权声明:任先阳 任 先 阳 任先 先阳,ifgm.cn、www.ifgm.cn、nvcc.cc、www.nvcc.cc、sbfox.com、www.sbfox.com https://blog.csdn.net/qq_39571197/article/details/85681832

'E:/**/lib/viser-vue/index.js'

使用后行断言匹配 E:/**/lib/viser-vue/,然后进行变量名称校验

1、

const filePath = 'E:/**/lib/viser-vue/index.js';
console.log(filePath.match(/.*(?=(\.js)$)/g)); // E:/**/lib/viser-vue/index

2、

const filePath = 'E:/**/lib/viser-vue/index.js';
console.log(filePath.match(/(?>=(.*\/))[_0-9a-zA-Z]+(?=(\.js)$)/g)); // index

3、测试,变量名称不能以数字开头

const fileNameReg = /(?<=.*\/)(?<varName>[_$a-zA-Z])+?([0-9\k<varName>]*)(?=\.js$)/g;
console.log('E:/**/lib/viser-vue/$index.js'.match(fileNameReg));
console.log('E:/**/lib/viser-vue/012384.js'.match(fileNameReg));
console.log('E:/**/lib/viser-vue/_12aaaa2.js'.match(fileNameReg));
console.log('a12aaaa2.js'.match(fileNameReg));

node是可以使用的,浏览器中使用,注:部分浏览器不支持后行断言

// const fileNameReg = /(?<=.*\/)(?<varName>[_$a-zA-Z])+?([0-9\k<varName>]*)(?=\.js$)/g;
const fileNameReg = /(?<=.*\/)[_$a-zA-Z]+?([_$a-zA-Z0-9]*)(?=\.js$)/g;
console.log('E:/**/lib/viser-vue/$index.js'.match(fileNameReg));
console.log('E:/**/lib/viser-vue/012384.js'.match(fileNameReg));
console.log('E:/**/lib/viser-vue/_12aaaa2.js'.match(fileNameReg));
console.log('a12aaaa2.js'.match(fileNameReg));
console.log(parseVarNameByFilePath('E:/**/lib/viser-vue/$index.js'));
console.log(parseVarNameByFilePath('E:/**/lib/viser-vue/012384.js'));
console.log(parseVarNameByFilePath('E:/**/lib/viser-vue/_12aaaa2.js'));
console.log(parseVarNameByFilePath('/1a12aaaa2.js'));

function parseVarNameByFilePath(path, ext = '.js') {
  path = path.split('/');
  path = path[path.length - 1];
  if (!path.endsWith(ext)) return null;
  if (!/[_$a-zA-Z]/.test(path[0])) return null;
  return path.slice(0, -ext.length);
}

猜你喜欢

转载自blog.csdn.net/qq_39571197/article/details/85681832