regex 使用lookaround查找模式的最后一次出现

kcugc4gi  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(39)

我的路径是../dir1/dir2/dir3/filename.txt,想用正则表达式在最后的\.之间只提取filename。文件扩展名也不总是.txt
目前我正在做(?<=\/).+(?=\.),但从第一个\中选择,包括目录名。我希望这只是基于匹配而不是使用组。哦,如果这很重要,请使用ECMA正则表达式。

vmjh9lq9

vmjh9lq91#

你可以使用下面的正则表达式来实现你的目的:

([\w-]+)\..*$

字符串

上述正则表达式的解释:
*([\w-]+)-捕获匹配一个或多个(+)单词字符(\w)或连字符(-)的组。通常文件名包含\w字符,所以我使用了它,但如果它包含其他特殊字符,请根据您的需要随时修改它。
*\.-匹配文字点字符。
.*-匹配任何字符(.)零次或多次()。
*$-匹配行尾。所以基本上完整的正则表达式匹配任何包含一个单词(由一个或多个单词字符或连字符组成)的字符串,后跟一个点和任何字符,直到行尾。点之前的单词被捕获以供以后使用,这个捕获组为您提供所需的filename

x1c 0d1x的数据

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

  • REGEX DEMO*
    替代方式:(使用JavaScript函数)
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.
*/

23c0lvtd

23c0lvtd2#

如果匹配正则表达式

\/(?:(\.?[^./][^/]*)\.[^./]+|(\.?[^./]+))$

字符串
或者:

  • 存在文件扩展名,在这种情况下,捕获组1将保存不带扩展名的基本文件,捕获组2将为空;或者
  • basket没有扩展,在这种情况下,捕获组2将保存basket,而捕获组1将为空。

Demo
我们可以把这个表达式分解如下。

\/         # 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


您可能还希望将鼠标悬停(光标,而不是您本人)在链接处的表达式的不同部分上,以获得对其功能的解释。
如果已知bascent有一个扩展,正则表达式将以一种显而易见的方式简化,只有一个捕获组:

(\.?[^/]+)\.[^./]+$


Demo

相关问题