[英]Regex match all characters except “.js”
I am trying to separate a module name from it's path, with javascript. 我正在尝试使用javascript将模块名称与其路径分开。 The string I am receiving the regex on may or may not have ".js" on the end, but in the 2nd matching group I need to not have the ".js" if it is there.
我正在接收正则表达式的字符串的末尾可能带有“ .js”,也可能没有,但是在第二个匹配组中,如果那里存在“ .js”,则不需要。 This is the regular expression so far:
到目前为止,这是正则表达式:
([\.\/]?.+\/)?(.+[\.js]?)
for example if I have the string: ./piechart.js 例如,如果我有字符串:./piechart.js
Match group 1: ./ 比赛组1:./
Match group 2: piechart 比赛组2:饼图
More test/example: https://regex101.com/r/nL9lK3/1 更多测试/示例: https : //regex101.com/r/nL9lK3/1
I'd suggest to filter the string first, then regex it to retrieve the module name. 我建议先过滤字符串,然后对其进行正则表达式以检索模块名称。
function getModule (filePath) {
var arr = filePath.split('/');
var len = arr.length;
var path = arr.splice(0, arr.length - 1).join('/');
var moduleName = arr[0].match(/([a-zA-Z\-\_]+)(?=(\.js)?)/gi)[0];
return [path, moduleName];
}
This function will return an array of path
and moduleName
. 此函数将返回
path
和moduleName
的数组。
So try this 所以试试这个
(\\/?.+\\/)*(.+?)(\\.js)?$
and use the first two matching groups only (here's the updated regex101 ). 并仅使用前两个匹配的组(这是更新的regex101 )。
First group: (\\/?.+\\/)*
matches all the possible paths, ending in a final slash. 第一组:
(\\/?.+\\/)*
匹配所有可能的路径,以最后一个斜杠结束。
Second group: (.+?)
matches everything following the path, but with a lazy quantifier, allowing the third group to match if it can. 第二组:
(.+?)
匹配路径中的所有内容,但带有一个惰性量词,如果可以的话,允许第三组进行匹配。
Third group: (\\.js)?
第三组:
(\\.js)?
matches a possible .js
at the end of the string. 在字符串末尾匹配可能的
.js
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.