const regex = /.*?([\w-]+)\..*$/gm;
const str = `../dir1/dir2/dir3/filename1.tar.gz
../dir1/dir2/dir3/filename2.tar`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
let paths = `../dir1/dir2/dir3/filename1.tar.gz
../dir1/dir2/dir3/filename2.tar`;
paths.split('\n').forEach(path => console.log(path.
split('/').pop().split('.').shift()));
/*
* split('/').pop() - splits the path into an array using the forward slash (/) as the separator
and removes and returns the last element of the array.
* split('.').shift() - splits the filename into an array using the dot (.) as the separator,
and removes and returns the first element of the array.
* NOTE: paths.split('\n') might not be your exact requirement. I used it to showcase.
*/
\/ # match a forward slash
(?: # begin non-capture group
( # begin capture group 1
\.? # optionally match a period (for hidden files)
[^/]+ # match one or more chars other than (`^`) a forward slash
) # end capture group 1
\. # match a period
[^./]+ # match one or more chars other than a period or forward slash
| # or
( # begin capture group 2
\.? # optionally match a period (for hidden files)
[^./]+ # match one or more chars other than a period or forward slash
) # end capture group 2
) # end non-capture group
$ # match the end of the string
2条答案
按热度按时间vmjh9lq91#
你可以使用下面的正则表达式来实现你的目的:
字符串
上述正则表达式的解释:
*
([\w-]+)
-捕获匹配一个或多个(+)单词字符(\w)或连字符(-)的组。通常文件名包含\w
字符,所以我使用了它,但如果它包含其他特殊字符,请根据您的需要随时修改它。*
\.
-匹配文字点字符。.*
-匹配任何字符(.)零次或多次()。*
$
-匹配行尾。所以基本上完整的正则表达式匹配任何包含一个单词(由一个或多个单词字符或连字符组成)的字符串,后跟一个点和任何字符,直到行尾。点之前的单词被捕获以供以后使用,这个捕获组为您提供所需的filename
。x1c 0d1x的数据
型
替代方式:(使用JavaScript函数)
型
23c0lvtd2#
如果匹配正则表达式
字符串
或者:
Demo
我们可以把这个表达式分解如下。
型
您可能还希望将鼠标悬停(光标,而不是您本人)在链接处的表达式的不同部分上,以获得对其功能的解释。
如果已知bascent有一个扩展,正则表达式将以一种显而易见的方式简化,只有一个捕获组:
型
Demo的