简体   繁体   English

使用正则表达式从路径中提取文件名

[英]Extract file name from a path using regular expression

How can I extract the string "XMLFileName" from the below URL using regular expression 如何使用正则表达式从下面的URL中提取字符串“ XMLFileName”

var x = "C:\Documents and Settings\Dig\Desktop\XMLFileName.xml"

Thanks 谢谢

You could do it with split() , pop() and replace() ... 您可以使用split()pop()replace()来做到这一点...

var filename = x.split('\\').pop().replace(/\..+$/, '');

jsFiddle . jsFiddle

You could also use a single regex... 您也可以使用单个正则表达式...

var filename = x.replace(/.*\\|\..*$/g, '');

jsFiddle . jsFiddle

Ensure you escape the \\ in your string literal too. 确保在字符串文字中也转义\\

trivial 不重要的

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

of course you weren't very specific, so while this will work for your particular case, I'm not here to read your mind. 当然,您不是很专一,因此尽管这对您的特定情况适用,但我并不是想了解您的想法。

You can use: " [^\\\\]*$ " 您可以使用:“ [^\\\\]*$

but why not using regular javascript functions like indexOf() etc. 但为什么不使用常规的JavaScript函数,例如indexOf()等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM