Regex: Get Filename Without Extension in One Shot?

后端 未结 7 1780
萌比男神i
萌比男神i 2020-12-03 03:20

I want to get just the filename using regex, so I\'ve been trying simple things like

([^\\.]*)

which of course work only if the filename ha

相关标签:
7条回答
  • 2020-12-03 03:59

    Just the name of the file, without path and suffix.

    ^.*[\\|\/](.+?)\.[^\.]+$
    
    0 讨论(0)
  • 2020-12-03 04:02

    Everything followed by a dot followed by one or more characters that's not a dot, followed by the end-of-string:

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

    The everything-before-the-last-dot is grouped for easy retrieval.

    If you aren't 100% sure every file will have an extension, try:

    (.+?)(\.[^\.]+$|$)
    
    0 讨论(0)
  • 2020-12-03 04:10
    ^(.*)\\(.*)(\..*)$
    
    1. Gets the Path without the last \
    2. The file without extension
    3. The the extension with a .

    Examples:

    c:\1\2\3\Books.accdb
    (c:\1\2\3)(Books)(.accdb)

    Does not support multiple . in file name Does support . in file path

    0 讨论(0)
  • 2020-12-03 04:12

    I used this pattern for simple search:

    ^\s*[^\.\W]+$
    

    for this text:

    file.ext
       fileext
    
       file.ext.ext
     file.ext
    fileext
    

    It finds fileext in the second and last lines.
    I applied it in a text tree view of a folder (with spaces as indents).

    0 讨论(0)
  • 2020-12-03 04:18

    Try this:

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

    This will:

    • Capture filenames that start with a dot (e.g. .logs is a file named .logs, not a file extension), which is common in Unix.
    • Gets everything but the last dot: foo.bar.jpeg gets you foo.bar.
    • Handles files with no dot: secret-letter gets you secret-letter.

    Note: as commenter j_random_hacker suggested, this performs as advertised, but you might want to precede things with an anchor for readability purposes.

    0 讨论(0)
  • 2020-12-03 04:21

    Ok, I am not sure why I would use regular expression for this. If I know for example that the string is a full filepath, then I would use another API to get the file name. Regular expressions are very powerfull but at the same time quite complex (you have just proved that by asking how to create such a simple regex). Somebody said: you had a problem that you decided to solve it using regular expressions. Now you have two problems.

    Think again. If you are on .NET platform for example, then take a look at System.IO.Path class.

    0 讨论(0)
提交回复
热议问题