简体   繁体   中英

Regular expression to Get Extension - .net

Environment - SharePoint Workflow (.net tech)

Trying to get extension of a file name (sometime it's doc or docx or dwg or xlsx).

I got this \\..+ or this \\.[^\\.]+$ to give me the file name. I need another expression that will give me the extension. I guess I need an expression that will look for the last period and give me the string.

Use Path.GetExtension(fileName) instead of creating regex - it looks last . in file name and returns substring with extension.

UPDATE: If it has to be regex, then try \\.[0-9a-z]+$

It would be something like:

@"(?<=\.)([^\\/.]*)$"

It means: ([^\\\\/.]*) any non-dot non-path character in any number, followed by end-of-the-string $ . The non-dot characters must be preceded by a dot (?<=\\.) that won't be captured. (so filename without extension are captured as having blank extension)

Note the escaping of the \\ inside the []

some funny test cases:

C:\My.Path\Filename
C:\My.Path\Filename.ext
C:\My.Path\Filename.ext.ext2
..\Filename
..\Filename.ext

Tester: http://regexr.com?361pu

I'll add that Path.GetExtensions is the right instrument to do this work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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