简体   繁体   English

正则表达式或 Substring 以匹配文件名和扩展名

[英]Regex or Substring to Match Filename With Extension

I have a current situation where I can be given a filename with path that looks like:我目前的情况是可以给我一个文件名,其路径如下:

C:\\Users\\testUser\\Documents\\testFile.txt.9043632d298f44ad88509c677a8249f8

or或者

C:\\Users\\testUser\\Documents\\testFile.txt.9043632d298f44ad88509c677a8249f8.enc

I need to be able to extract everything up until the end of the extension (can be any file extension, will always have guid string preceded by a. after the extension)我需要能够提取所有内容直到扩展名结束(可以是任何文件扩展名,总是有 guid 字符串前面有一个。在扩展名之后)

So an example output would be:因此,示例 output 将是:

C:\\Users\\testUser\\Documents\\testFile.txt
C:\\Users\\testUser\\Documents\\testFile.pdf
C:\\Users\\testUser\\Documents\\testFile.jpeg

I have tried substrings but cannot seem to get the proper input (though I assume it is a simple task).我已经尝试过子字符串,但似乎无法获得正确的输入(尽管我认为这是一项简单的任务)。 I can never seem to get the proper result.我似乎永远无法得到正确的结果。

An example I tried was along the lines of:我试过的一个例子是:

filename.Substring(0,filename.Indexof('.', //what goes here??));

but keep getting stuck.但一直卡住。

Any help would be lovely!任何帮助都会很可爱!

You might use:您可能会使用:

new Regex(@".*(?=\.[a-f\d]{32})", RegexOptions.IgnoreCase).Match(yourString)

Explanation :说明

.+ match one or more of any char .+ 匹配一个或多个任意字符

(?= ) look ahead, check if the following chars match, but don't include in match (?= )向前看,检查以下字符是否匹配,但不包含在匹配中

\. match a dot匹配一个点

[af\d]{32} match any character af or digit exactly 32 times [af\d]{32}匹配任意字符afdigit 32 次

RegexOptions.IgnoreCase ignores the case RegexOptions.IgnoreCase忽略大小写

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

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