fileName
,也就是说,在 C://Directory/FileName.cs
中,使用正则表达式忽略 FileName.cs
之前的所有内容。我该怎么做呢?
我需要这个功能用于我正在开发的已编译的 UI ... 不能使用编程语言,因为它只接受正则表达式。
有什么想法吗?
fileName
,也就是说,在 C://Directory/FileName.cs
中,使用正则表达式忽略 FileName.cs
之前的所有内容。可能类似这样的代码可以起作用:
[^/]*$
它匹配所有不是"/"的字符直到行尾。
如果您想匹配使用 "\" 路径分隔符的路径,则需要将正则表达式更改为:
[^\]*$
如果您的编程语言或环境要求,请确保转义“\”字符。例如,您可能需要编写类似于以下内容的内容:
[^\\]*$
编辑: 我删除了开头和结尾处的“/”,因为它们可能会让人困惑,因为它们实际上不是正则表达式的一部分,但它们通常用于表示正则表达式。
当然,根据regEx引擎支持的功能,您可以使用向前/向后查找和捕获等功能来制作更好的正则表达式。
根据您的评论,需要排除与“abc”不匹配的路径,请尝试以下方法:
^.+/(?:(?!abc)[^/])+$
完全分割在正则表达式注释模式中,即:
(?x) # flag to enable comments
^ # start of line
.+ # match any character (except newline)
# greedily one or more times
/ # a literal slash character
(?: # begin non-capturing group
(?! # begin negative lookahead
# (contents must not appear after the current position)
abc # literal text abc
) # end negative lookahead
[^/] # any character that is not a slash
) # end non-capturing group
+ # repeat the above nc group one or more times
# (essentially, we keep looking for non-backspaces that are not 'abc')
$ # end of line
对我起作用的正则表达式是
[^\/]*$
尝试使用以下方法:
public string ConvertFileName(string filename)
{
string[] temparray = filename.Split('\\');
filename = temparray[temparray.Length - 1];
return filename;
}
.+?\\(?=\w+)|\.\w+$|\\$
之前:
C:\Directory\BaseFileName.ext
C:\Directory\BaseFileName
C:\This is a Directory\Last Directory With trailing backslash\
C:\This is a Directory\Last Directory Without trailing backslash
之后:
BaseFileName
BaseFileName
Last Directory With trailing backslash
Last Directory Without trailing backslash
// Example of getting a BaseFileName from a path
var path = "C:\\Directory\\FileName.cs";
var result = path.replace(/.+?\\(?=\w+)|\.\w+$|\\$/gm,"");
console.log(result);
我在Powershell中没有使用RegEx完成了这个操作:
$Link = "http://some.url/some/path/file.name"
$split = $Link.Split("/")
$SplitCount = $Split.Count
$Split[$SplitCount -1]
完整代码:
$Link = "http://some.url/some/path/file.name"
$Split = $Link.Split("/")
$SplitCount = $Split.Count
$Split[$SplitCount -1]
在IE中,当文件上传时,文件路径也包含文件夹(例如c:\samplefolder\subfolder\sample.xls)。下面的表达式将用空字符串替换所有文件夹并保留文件名:
在Mac中使用时,只提供文件名,因为它是Safari浏览器,并允许文件名中包含特殊字符。
var regExpDir = @"(^[\w]:\\)([\w].+\w\\)";
var fileName = Regex.Replace(fileName, regExpDir, string.Empty);
我会使用:/(.$)
括号标记了一个组,这是文件名。 您使用的正则表达式可能因正则表达式语法(PCRE、POSIX)而异。
我建议您使用正则表达式工具,Windows 和 Linux 上都有几个:
Windows - http://sourceforge.net/projects/regexcreator/
Windows - http://weitz.de/regex-coach/
Linux - kodos
希望能帮到您